-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
103 lines (85 loc) · 1.93 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package main
import (
"bufio"
"crypto/x509"
"encoding/json"
"encoding/pem"
"errors"
"flag"
"fmt"
"io"
"os"
"github.com/golang-jwt/jwt/v5"
)
func readPrivateKey(filename string) (any, error) {
file, err := os.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()
b := bufio.NewReader(file)
raw, err := io.ReadAll(b)
if err != nil {
return nil, err
}
// parse PEM ECDSA private key
block, _ := pem.Decode(raw)
if block == nil {
return nil, errors.New("failed to parse PEM block containing the private key")
}
return x509.ParseECPrivateKey(block.Bytes)
}
func readJWTAssertion(filename string) (map[string]any, error) {
file, err := os.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()
b := bufio.NewReader(file)
raw, err := io.ReadAll(b)
if err != nil {
return nil, err
}
out := map[string]any{}
err = json.Unmarshal(raw, &out)
if err != nil {
return nil, err
}
return out, nil
}
func createToken(claims map[string]any, key any) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodES256, jwt.MapClaims(claims))
// Sign with jwt instead of JWT
token.Header["typ"] = "jwt"
tokenString, err := token.SignedString(key)
if err != nil {
return "", err
}
return tokenString, nil
}
func main() {
keyFile := flag.String("private-ec-key-file", "", "path to the private key file")
assertionFile := flag.String("assertion-file", "", "path to the JWT assertion file")
flag.Parse()
if keyFile == nil || *keyFile == "" {
panic("missing required flag: -private-ec-key-file")
}
if assertionFile == nil || *assertionFile == "" {
panic("missing required flag: -assertion-file")
}
key, err := readPrivateKey(*keyFile)
if err != nil {
panic(err)
}
// read JWT assertion
jwt, err := readJWTAssertion(*assertionFile)
if err != nil {
panic(err)
}
// sign JWT assertion
token, err := createToken(jwt, key)
if err != nil {
panic(err)
}
fmt.Println(token)
}