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 104 105
| package main
import ( "crypto/rsa" _ "embed" "encoding/base64" "encoding/json" "fmt" "math/big" "time"
"github.com/dgrijalva/jwt-go" )
type PublicKey struct { Kty string `json:"kty"` E string `json:"e"` N string `json:"n"` }
type PrivateKey struct { PublicKey D string `json:"d"` Qi string `json:"qi"` Q string `json:"q"` Dp string `json:"dp"` Dq string `json:"dq"` }
var keyJSON string
func genJwt() {
var privateKey PrivateKey err := json.Unmarshal([]byte(keyJSON), &privateKey) if err != nil { fmt.Printf("Failed to parse key JSON: %v\n", err) return }
nBytes, err := base64.RawURLEncoding.DecodeString(privateKey.N) if err != nil { fmt.Printf("Failed to decode modulus: %v\n", err) return } dBytes, err := base64.RawURLEncoding.DecodeString(privateKey.D) if err != nil { fmt.Printf("Failed to decode private exponent: %v\n", err) return } eBytes, err := base64.RawURLEncoding.DecodeString(privateKey.E) if err != nil { fmt.Printf("Failed to decode public exponent: %v\n", err) return }
rsaPrivateKey := &rsa.PrivateKey{ PublicKey: rsa.PublicKey{ N: rsaDecode(nBytes), E: int(extractBigEndianValue(eBytes)), }, D: rsaDecode(dBytes), Primes: []*big.Int{ rsaDecode([]byte(privateKey.Q)), }, Precomputed: rsa.PrecomputedValues{}, }
claims := jwt.StandardClaims{ Subject: "user123", ExpiresAt: time.Now().Add(time.Minute * 10).Unix(), }
token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims) signedToken, err := token.SignedString(rsaPrivateKey) if err != nil { fmt.Printf("Failed to sign token: %v\n", err) return }
fmt.Println(signedToken) }
func rsaDecode(data []byte) *big.Int { var result big.Int result.SetBytes(data) return &result }
func extractBigEndianValue(data []byte) uint64 { value := uint64(0) for _, b := range data { value = (value << 8) + uint64(b) } return value }
|