github.com/blend/go-sdk@v1.20220411.3/jwk/jwk.go (about) 1 /* 2 3 Copyright (c) 2021 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package jwk 9 10 import ( 11 "crypto/rsa" 12 "encoding/base64" 13 "math/big" 14 ) 15 16 type ( 17 // Set represents a set of JWKs as defined by https://tools.ietf.org/html/rfc7517#section-5 18 Set struct { 19 Keys []JWK `json:"keys"` 20 } 21 22 // JWK represents a cryptographic key as defined by https://tools.ietf.org/html/rfc7517#section-4 23 JWK struct { 24 KTY string `json:"kty"` 25 USE string `json:"use,omitempty"` 26 ALG string `json:"alg,omitempty"` 27 KID string `json:"kid,omitempty"` 28 E string `json:"e,omitempty"` 29 N string `json:"n,omitempty"` 30 } 31 ) 32 33 // RSAPublicKey parses the public key in the JWK to a rsa.PublicKey. 34 func (j JWK) RSAPublicKey() (*rsa.PublicKey, error) { 35 decodedE, err := base64.RawURLEncoding.DecodeString(j.E) 36 if err != nil { 37 return nil, err 38 } 39 decodedN, err := base64.RawURLEncoding.DecodeString(j.N) 40 if err != nil { 41 return nil, err 42 } 43 44 var n, e big.Int 45 e.SetBytes(decodedE) 46 n.SetBytes(decodedN) 47 return &rsa.PublicKey{ 48 E: int(e.Int64()), 49 N: &n, 50 }, nil 51 } 52 53 // KTY parameter values as defined in https://tools.ietf.org/html/rfc7518#section-6.1 54 const ( 55 KTYRSA = "RSA" 56 ) 57 58 // RSAPublicKeyToJWK converts an RSA public key to a JWK. 59 func RSAPublicKeyToJWK(key *rsa.PublicKey) JWK { 60 return JWK{ 61 KTY: KTYRSA, 62 E: base64.RawURLEncoding.EncodeToString(big.NewInt(int64(key.E)).Bytes()), 63 N: base64.RawURLEncoding.EncodeToString(key.N.Bytes()), 64 } 65 }