I am trying to validate a JWT from Apple in Go and I need their public key as Go's rsa.PublicKey to do so. I retrieved their keys from the endpoint specified in:
https://developer.apple.com/documentation/sign_in_with_apple/fetch_apple_s_public_key_for_verifying_token_signature
and got the following:
{
"keys": [
{
"kty": "RSA",
"kid": "86D88Kf",
"use": "sig",
"alg": "RS256",
"n": "iGaLqP6y-SJCCBq5Hv6pGDbG_SQ11MNjH7rWHcCFYz4hGwHC4lcSurTlV8u3avoVNM8jXevG1Iu1SY11qInqUvjJur--hghr1b56OPJu6H1iKulSxGjEIyDP6c5BdE1uwprYyr4IO9th8fOwCPygjLFrh44XEGbDIFeImwvBAGOhmMB2AD1n1KviyNsH0bEB7phQtiLk-ILjv1bORSRl8AK677-1T8isGfHKXGZ_ZGtStDe7Lu0Ihp8zoUt59kx2o9uWpROkzF56ypresiIl4WprClRCjz8x6cPZXU2qNWhu71TQvUFwvIvbkE1oYaJMb0jcOTmBRZA2QuYw-zHLwQ",
"e": "AQAB"
},
{
"kty": "RSA",
"kid": "eXaunmL",
"use": "sig",
"alg": "RS256",
"n": "4dGQ7bQK8LgILOdLsYzfZjkEAoQeVC_aqyc8GC6RX7dq_KvRAQAWPvkam8VQv4GK5T4ogklEKEvj5ISBamdDNq1n52TpxQwI2EqxSk7I9fKPKhRt4F8-2yETlYvye-2s6NeWJim0KBtOVrk0gWvEDgd6WOqJl_yt5WBISvILNyVg1qAAM8JeX6dRPosahRVDjA52G2X-Tip84wqwyRpUlq2ybzcLh3zyhCitBOebiRWDQfG26EH9lTlJhll-p_Dg8vAXxJLIJ4SNLcqgFeZe4OfHLgdzMvxXZJnPp_VgmkcpUdRotazKZumj6dBPcXI_XID4Z4Z3OM1KrZPJNdUhxw",
"e": "AQAB"
}
]
}
I've tried the x509.ParsePKCS1PublicKey(...) function by parsing both the individual key and the entire JSON returned using asn1.Marshall(...) function. I got an error trying to parse the der.
I then noticed that the key contains "n" and "e" string pairs, and are defined here so I tried to create the public key directly. However, N and E in the rsa.PublicKey are a *big.Int and int respectively.
I can't seem to find the encoding for "n" and "e", so I can't accurately convert the values to an rsa.PublicKey. I've tried base64, but that did not work.
Can anyone tell me how I can convert Apple's public key to a suitable rsa.PublicKey please?
The values of "n" and "e" in your JSON are just base64-encoded big-endian binary integers, so once you've decoded them you can convert them to type *big.Int with big.Int.SetBytes, and then use those to populate an *rsa.PublicKey.
You mentioned you tried base64 and it didn't work, but you need to make sure you use the right encoding and padding options- the presence of - and _ characters in the encoded string indicates that you're dealing with the RFC 4648 URL-safe encoding, and the fact that the length of the string is not divisible by 4 indicates that no padding characters are present, so therefore base64.URLEncoding.WithPadding(base64.NoPadding) is what you need to use.
Comprehensive example of a type you can directly unmarshal into and convert:
package main
import (
"crypto/rsa"
"encoding/base64"
"encoding/json"
"log"
"math/big"
)
const keyJSON = `{
"kty": "RSA",
"kid": "86D88Kf",
"use": "sig",
"alg": "RS256",
"n": "4dGQ7bQK8LgILOdLsYzfZjkEAoQeVC_aqyc8GC6RX7dq_KvRAQAWPvkam8VQv4GK5T4ogklEKEvj5ISBamdDNq1n52TpxQwI2EqxSk7I9fKPKhRt4F8-2yETlYvye-2s6NeWJim0KBtOVrk0gWvEDgd6WOqJl_yt5WBISvILNyVg1qAAM8JeX6dRPosahRVDjA52G2X-Tip84wqwyRpUlq2ybzcLh3zyhCitBOebiRWDQfG26EH9lTlJhll-p_Dg8vAXxJLIJ4SNLcqgFeZe4OfHLgdzMvxXZJnPp_VgmkcpUdRotazKZumj6dBPcXI_XID4Z4Z3OM1KrZPJNdUhxw",
"e": "AQAB"
}`
// decodeBase64BigInt decodes a base64-encoded larger integer from Apple's key format.
func decodeBase64BigInt(s string) *big.Int {
buffer, err := base64.URLEncoding.WithPadding(base64.NoPadding).DecodeString(s)
if err != nil {
log.Fatalf("failed to decode base64: %v", err)
}
return big.NewInt(0).SetBytes(buffer)
}
// appleKey is a type of public key.
type appleKey struct {
KTY string
KID string
Use string
Alg string
N *big.Int
E int
}
// UnmarshalJSON parses a JSON-encoded value and stores the result in the object.
func (k *appleKey) UnmarshalJSON(b []byte) error {
var tmp struct {
KTY string `json:"kty"`
KID string `json:"kid"`
Use string `json:"use"`
Alg string `json:"alg"`
N string `json:"n"`
E string `json:"e"`
}
if err := json.Unmarshal(b, &tmp); err != nil {
return err
}
*k = appleKey{
KTY: tmp.KTY,
KID: tmp.KID,
Use: tmp.Use,
Alg: tmp.Alg,
N: decodeBase64BigInt(tmp.N),
E: int(decodeBase64BigInt(tmp.E).Int64()),
}
return nil
}
// RSA returns a corresponding *rsa.PublicKey
func (k appleKey) RSA() *rsa.PublicKey {
return &rsa.PublicKey{
N: k.N,
E: k.E,
}
}
func main() {
// Decode the Apple key.
var ak appleKey
if err := json.Unmarshal([]byte(keyJSON), &ak); err != nil {
log.Fatalf("failed to unmarshal JSON: %v", err)
}
// Convert it to a normal *rsa.PublicKey.
rk := ak.RSA()
if rk.Size() != 256 {
log.Fatalf("unexpected key size: %d", rk.Size())
}
// Do what you like with the RSA key now.
}
Related
As the title says, I have a JSON file generated based on https://mkjwk.org/ and now I want to use the generated values to sign a JWT. I will do this for multiple "clients", each with its own signature.
These will then be verified against a set of JWKS containing the public keys for the different "clients".
However, I'm struggling to understand how to use the generated JSON values..
I know I can generate one priv/pub keys directly with the crypto/rsa module. I've also seen examples where the ppk is given as input in X509 format, though I was trying to avoid it if possible (I guess I'm just being picky as I prefer to be able to read the contents of a file rather than seeing random chars..)
From the multiple examples and numerous searches I've done, I haven't seen one where the process of taking a json file and generating a rsa.privateKey is performed.
I'm also using the jwt-go and jwx modules to handle the rest of the use cases, but this one is escaping me..
So, what am I missing? How can I go from a JSON like the one below to a rsa.PrivateKey?
{
"p": "vQXloZI9y5..._PPE6m05J-VqhIF6-FQjvwc",
"kty": "RSA",
"q": "u1OqnCCLyEZDMoSfK...SfcIGNSd90PEcPs",
"d": "eoAj0Z0PkK3A0pc5t...9Q8iqGntoxMVARBtQ",
"e": "AQAB",
"use": "sig",
"kid": "r9cuFC3...HiAc7VhSME",
"qi": "upOjfCF_na...H4a7Bs2pWGoS6w5mcqXU",
"dp": "HKGzCclEEP...GdofDVR5Yas",
"alg": "RS256",
"dq": "PDyRNhc5G7OMVChVTm61kn2ShRFTe...BLytOxGBm5ntJv4V0HRBU",
"n": "ilEVn6tSuh7-tZBV8qXmlvzWDE5jTS...sNH8-wPf6gKCuZzEyyS2AyZE8S4NzqoFkaepVpdoOPtb3Q"
}
Thanks
The jwx package has a function to parse a JWK:
func ParseString(s string)
You can use it to parse the JWK like this, and use the key to sign and verify a JWT (pay attention to the code comments for further details):
package main
import(
"log"
"github.com/lestrrat-go/jwx/jwk"
"github.com/lestrrat-go/jwx/jws"
"github.com/lestrrat-go/jwx/jwa"
)
func main() {
// Here's an example of a JWK, containing a public and private RSA Keypair
var keysJWK = `{
"keys": [
{
"p": "59pSssPVWNBMd1dFBhkSx0P6uo3b3WC2MOitj7UI-9VS9gKPbPsqtDJSPdbRjK7JWXarFt_h4aPf9NPFLieu1k22jp3ProCH87geazJ8tNtV_SpaUtWQFZ-dvgGrIM-3MLf_fG7Tq5sV5R0vA9wg_INkYJ2uX5EdmVyHhxvh0eM",
"kty": "RSA",
"q": "jeofLDkteXfWcpif3JmX3xv8S6jWX2Axrwe9tLkWzlgxYDWvXExxD0sc4XfbVbSrqTkAdW48DYL_wcziFLYHxOYv2stqWvElF9CqdKJJrQAc7Z_qKXpWckDYZBJAO9W2WGXTBfdJfw_KQPHHTbY90ngdxMXuiwYbfbFY4H_XDM0",
"d": "Qrx8U40tLhsy4tdnKuEmjlGF-VkB6F_DawLXwuZ2a5ZS7cwFUDRHNz9Jbl9MxvNcNMSMGaAN8lxTSDlpfT0jDqKF6lel88rUtCnN6h1FNdkD5TjkbWs-dfhftDFc1Sy8RdWPZ8LiTo0TbZaf3rPvdLw_S9FE-itnKV_1il572rT-1PvlyrPctnREQCKL5wArD4eYHwRjfVm-KvlIvo9rLj4NYzATBAAwh6PsEnSganEf1ErOvFH8qhrVqsy2kevLsFbCA0hIfoDNhL7hxlaMSJTJie3V2Ie0Kb7j_L2LsQXka3kshO1T6re-d-nGgaRp7b0buUtwS6aTax0H2cZuOQ",
"e": "AQAB",
"use": "sig",
"kid": "223",
"qi": "moGHNM3TFLeSQeM6V4izMcK6wwapSwo67r7DXk7vK_2FaSUQtijwQCHFx3nrhbQAVdwFt7pSYlmlFPlaAXixrBBNtNULnR7z6-WrRuWgqoL9LN8xARB42l94HmiOL0pp8ORyw2W338k3LHuzUy1NKZrL6a8zPIkva_Z5hFULhQE",
"dp": "TcUm3j3gL3VXYOSOC5iXeu2ria4R5PUOx-MUbNLd25NXy5taPsUVMvJ6MbIAAj-S3IZ4pyib3RMaCUaLqoq3E71nkfkPc8o7UB4fXffGaufztQLi30wxk39B6z0mCNCD8zyU30lRiQtxUbPzVEkfa3QrVFkv53CGzC2EbGaG3d8",
"alg": "RS256",
"dq": "L1emNJOShw4iXTJrSiV3E7f7T6YwdbraeECF2c9RO18Sgb0HFixuHyL4rILWid3u0lIww_wVTpCgD5_w3-Xl65q65iur_FCsBijXZHdrSqpZ_C-350RnqE_XoHKyOQPPg-fcIQZg32F-IHJIAbXFI_xsOeOp83kDHMhYFPSw4hU",
"n": "gIdJV4qWKyt3wkS66yBG5Ii9ew-eofuPU49TjlRIU5Iu5jX2mRMoHdcI7V78iKYSQHKYxz17cqzQyERxKnEiDgy_gwouStRgvPdm3H4rq__7p0t15SunsG2T1rEVf0sZEDnQ5qRkm7iqs6ZG1NqqIUtnOTd1Pd1MhbEqeENFtaPHvN37eZL82WmsQlJviFH4I9iZQVR_QT4GREQlRro8IjJTaloUyeDQTOQ-4ll1-4-g_ug2tZ-s9xleLzl5L9ZKSVJFhtMLn8WGaVldagarwa7kMLfuiVe8B5Lr7poQa4NCAR54ECPWoOHrABdPZKrkkxjVypTXUzL5cPzmzFC2xw"
}
]
}`
// Parse the JWK to a set of keys
setOfKeys, err := jwk.ParseString(keysJWK )
if err != nil {
log.Printf("failed to parse JWK: %s", err)
return
}
// extract the private key from the set, index 0 because w only have one key
rsaPrivatekey, success := setOfKeys.Get(0)
if !success {
log.Printf("could not find key at given index")
return
}
// sign a token with the private key
token, err := jws.Sign([]byte(`{"userId":1}`), jwa.RS256, rsaPrivatekey)
if err != nil {
log.Printf("failed to created JWS message: %s", err)
return
}
// show the signed token
log.Printf("Token! -> %s", token)
// get a public key from a private key
rsaPublicKey, err := jwk.PublicKeyOf(rsaPrivatekey)
if err != nil {
log.Printf("failed created public key from private key: %s", err)
return
}
// verify the token that we created above with the public key
payload, err := jws.Verify(token, jwa.RS256, rsaPublicKey)
if err != nil {
log.Printf("failed to verify message: %s", err)
return
}
// show the payload of the verified token
log.Printf("signature verified! Payload -> %s", payload)
}
try it on the Go Playground
EDIT
This is the working code incase someone finds it useful. The title to this question was originally
"How to parse a list fo dicts in golang".
This is title is incorrect because I was referencing terms I'm familiar with in python.
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
)
//Regional Strut
type Region []struct {
Region string `json:"region"`
Description string `json:"Description"`
ID int `json:"Id"`
Name string `json:"Name"`
Status int `json:"Status"`
Nodes []struct {
NodeID int `json:"NodeId"`
Code string `json:"Code"`
Continent string `json:"Continent"`
City string `json:"City"`
} `json:"Nodes"`
}
//working request and response
func main() {
url := "https://api.geo.com"
// Create a Bearer string by appending string access token
var bearer = "TOK:" + "TOKEN"
// Create a new request using http
req, err := http.NewRequest("GET", url, nil)
// add authorization header to the req
req.Header.Add("Authorization", bearer)
//This is what the response from the API looks like
//regionJson := `[{"region":"GEO:ABC","Description":"ABCLand","Id":1,"Name":"ABCLand [GEO-ABC]","Status":1,"Nodes":[{"NodeId":17,"Code":"LAX","Continent":"North America","City":"Los Angeles"},{"NodeId":18,"Code":"LBC","Continent":"North America","City":"Long Beach"}]},{"region":"GEO:DEF","Description":"DEFLand","Id":2,"Name":"DEFLand","Status":1,"Nodes":[{"NodeId":15,"Code":"NRT","Continent":"Asia","City":"Narita"},{"NodeId":31,"Code":"TYO","Continent":"Asia","City":"Tokyo"}]}]`
//Send req using http Client
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Println("Error on response.\n[ERROR] -", err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println("Error while reading the response bytes:", err)
}
var regions []Region
json.Unmarshal([]byte(body), ®ions)
fmt.Printf("Regions: %+v", regions)
}
Have a look at this playground example for some pointers.
Here's the code:
package main
import (
"encoding/json"
"log"
)
func main() {
b := []byte(`
[
{"key": "value", "key2": "value2"},
{"key": "value", "key2": "value2"}
]`)
var mm []map[string]string
if err := json.Unmarshal(b, &mm); err != nil {
log.Fatal(err)
}
for _, m := range mm {
for k, v := range m {
log.Printf("%s [%s]", k, v)
}
}
}
I reformatted the API response you included because it is not valid JSON.
In Go it's necessary to define types to match the JSON schema.
I don't know why the API appends % to the end of the result so I've ignored that. If it is included, you will need to trim the results from the file before unmarshaling.
What you get from the unmarshaling is a slice of maps. Then, you can iterate over the slice to get each map and then iterate over each map to extract the keys and values.
Update
In your updated question, you include a different JSON schema and this change must be reflect in the Go code by update the types. There are some other errors in your code. Per my comment, I encourage you to spend some time learning the language.
package main
import (
"bytes"
"encoding/json"
"io/ioutil"
"log"
)
// Response is a type that represents the API response
type Response []Record
// Record is a type that represents the individual records
// The name Record is arbitrary as it is unnamed in the response
// Golang supports struct tags to map the JSON properties
// e.g. JSON "region" maps to a Golang field "Region"
type Record struct {
Region string `json:"region"`
Description string `json:"description"`
ID int `json:"id"`
Nodes []Node
}
type Node struct {
NodeID int `json:"NodeId`
Code string `json:"Code"`
}
func main() {
// A slice of byte representing your example response
b := []byte(`[{
"region": "GEO:ABC",
"Description": "ABCLand",
"Id": 1,
"Name": "ABCLand [GEO-ABC]",
"Status": 1,
"Nodes": [{
"NodeId": 17,
"Code": "LAX",
"Continent": "North America",
"City": "Los Angeles"
}, {
"NodeId": 18,
"Code": "LBC",
"Continent": "North America",
"City": "Long Beach"
}]
}, {
"region": "GEO:DEF",
"Description": "DEFLand",
"Id": 2,
"Name": "DEFLand",
"Status": 1,
"Nodes": [{
"NodeId": 15,
"Code": "NRT",
"Continent": "Asia",
"City": "Narita"
}, {
"NodeId": 31,
"Code": "TYO",
"Continent": "Asia",
"City": "Tokyo"
}]
}]`)
// To more closely match your code, create a Reader
rdr := bytes.NewReader(b)
// This matches your code, read from the Reader
body, err := ioutil.ReadAll(rdr)
if err != nil {
// Use Printf to format strings
log.Printf("Error while reading the response bytes\n%s", err)
}
// Initialize a variable of type Response
resp := &Response{}
// Try unmarshaling the body into it
if err := json.Unmarshal(body, resp); err != nil {
log.Fatal(err)
}
// Print the result
log.Printf("%+v", resp)
}
I'm using JWKS format to provide from an authentication service the public key that can be used to validate tokens coming from that authentication service. However, to perform validation I need to rebuild the public key from the JWK. How can I convert it?
type JWKeys struct {
Keys []JWKey `json:"keys"`
}
type JWKey struct {
Kty string `json:"kty"`
Use string `json:"use,omitempty"`
Kid string `json:"kid,omitempty"`
Alg string `json:"alg,omitempty"`
Crv string `json:"crv,omitempty"`
X string `json:"x,omitempty"`
Y string `json:"y,omitempty"`
D string `json:"d,omitempty"`
N string `json:"n,omitempty"`
E string `json:"e,omitempty"`
K string `json:"k,omitempty"`
}
var PublicKey *rsa.PublicKey
func SetUpExternalAuth() {
res, err := http.Get("my_url")
if err != nil {
log.Fatal("Can't retrieve the key for authentication")
}
bodyBytes, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Fatal(err)
}
var keys JWKeys
json.Unmarshal(bodyBytes, &keys)
//CONVERT JWK TO *rsa.PUBLICKEY???
}
UPDATE
I tried to parse the JWKs using github.com/lestrrat-go/jwx/jwk library, however I couldn't find how to continue:
set,err := jwk.Parse(bodyBytes)
key,err2 := set.Get(0)
//HOW TO CONVERT KEY INTO A *rsa.PublicKey?
At the end I've manually converted it:
if singleJWK.Kty != "RSA" {
log.Fatal("invalid key type:", singleJWK.Kty)
}
// decode the base64 bytes for n
nb, err := base64.RawURLEncoding.DecodeString(singleJWK.N)
if err != nil {
log.Fatal(err)
}
e := 0
// The default exponent is usually 65537, so just compare the
// base64 for [1,0,1] or [0,1,0,1]
if singleJWK.E == "AQAB" || singleJWK.E == "AAEAAQ" {
e = 65537
} else {
// need to decode "e" as a big-endian int
log.Fatal("need to deocde e:", singleJWK.E)
}
PublicKey = &rsa.PublicKey{
N: new(big.Int).SetBytes(nb),
E: e,
}
Understand you have a solution but as you were making the attempt using github.com/lestrrat-go/jwx/jwk here is an approach with that package (pretty much what is in the example):
package main
import (
"context"
"crypto/rsa"
"fmt"
"log"
"github.com/lestrrat-go/jwx/jwk"
)
func main() {
// Example jwk from https://www.googleapis.com/oauth2/v3/certs (but with only one cert for simplicity)
jwkJSON := `{
"keys": [
{
"kty": "RSA",
"n": "o76AudS2rsCvlz_3D47sFkpuz3NJxgLbXr1cHdmbo9xOMttPMJI97f0rHiSl9stltMi87KIOEEVQWUgMLaWQNaIZThgI1seWDAGRw59AO5sctgM1wPVZYt40fj2Qw4KT7m4RLMsZV1M5NYyXSd1lAAywM4FT25N0RLhkm3u8Hehw2Szj_2lm-rmcbDXzvjeXkodOUszFiOqzqBIS0Bv3c2zj2sytnozaG7aXa14OiUMSwJb4gmBC7I0BjPv5T85CH88VOcFDV51sO9zPJaBQnNBRUWNLh1vQUbkmspIANTzj2sN62cTSoxRhSdnjZQ9E_jraKYEW5oizE9Dtow4EvQ",
"use": "sig",
"alg": "RS256",
"e": "AQAB",
"kid": "6a8ba5652a7044121d4fedac8f14d14c54e4895b"
}
]
}
`
set, err := jwk.Parse([]byte(jwkJSON))
if err != nil {
panic(err)
}
fmt.Println(set)
for it := set.Iterate(context.Background()); it.Next(context.Background()); {
pair := it.Pair()
key := pair.Value.(jwk.Key)
var rawkey interface{} // This is the raw key, like *rsa.PrivateKey or *ecdsa.PrivateKey
if err := key.Raw(&rawkey); err != nil {
log.Printf("failed to create public key: %s", err)
return
}
// We know this is an RSA Key so...
rsa, ok := rawkey.(*rsa.PublicKey)
if !ok {
panic(fmt.Sprintf("expected ras key, got %T", rawkey))
}
// As this is a demo just dump the key to the console
fmt.Println(rsa)
}
}
I wrote a Go package exactly for this purpose: github.com/MicahParks/keyfunc
Converting to a *rsa.PublicKey
In this pacakge a JSON Web Key (JWK) looks like this Go struct. It supports both ECDSA and RSA JWK.
// JSONKey represents a raw key inside a JWKS.
type JSONKey struct {
Curve string `json:"crv"`
Exponent string `json:"e"`
ID string `json:"kid"`
Modulus string `json:"n"`
X string `json:"x"`
Y string `json:"y"`
precomputed interface{}
}
After the raw JSON message is unmarshaled into the above struct, this method converts it to an *rsa.PublicKey.
package keyfunc
import (
"crypto/rsa"
"encoding/base64"
"fmt"
"math/big"
)
const (
// rs256 represents a public cryptography key generated by a 256 bit RSA algorithm.
rs256 = "RS256"
// rs384 represents a public cryptography key generated by a 384 bit RSA algorithm.
rs384 = "RS384"
// rs512 represents a public cryptography key generated by a 512 bit RSA algorithm.
rs512 = "RS512"
// ps256 represents a public cryptography key generated by a 256 bit RSA algorithm.
ps256 = "PS256"
// ps384 represents a public cryptography key generated by a 384 bit RSA algorithm.
ps384 = "PS384"
// ps512 represents a public cryptography key generated by a 512 bit RSA algorithm.
ps512 = "PS512"
)
// RSA parses a JSONKey and turns it into an RSA public key.
func (j *JSONKey) RSA() (publicKey *rsa.PublicKey, err error) {
// Check if the key has already been computed.
if j.precomputed != nil {
return j.precomputed.(*rsa.PublicKey), nil
}
// Confirm everything needed is present.
if j.Exponent == "" || j.Modulus == "" {
return nil, fmt.Errorf("%w: rsa", ErrMissingAssets)
}
// Decode the exponent from Base64.
//
// According to RFC 7518, this is a Base64 URL unsigned integer.
// https://tools.ietf.org/html/rfc7518#section-6.3
var exponent []byte
if exponent, err = base64.RawURLEncoding.DecodeString(j.Exponent); err != nil {
return nil, err
}
// Decode the modulus from Base64.
var modulus []byte
if modulus, err = base64.RawURLEncoding.DecodeString(j.Modulus); err != nil {
return nil, err
}
// Create the RSA public key.
publicKey = &rsa.PublicKey{}
// Turn the exponent into an integer.
//
// According to RFC 7517, these numbers are in big-endian format.
// https://tools.ietf.org/html/rfc7517#appendix-A.1
publicKey.E = int(big.NewInt(0).SetBytes(exponent).Uint64())
// Turn the modulus into a *big.Int.
publicKey.N = big.NewInt(0).SetBytes(modulus)
// Keep the public key so it won't have to be computed every time.
j.precomputed = publicKey
return publicKey, nil
}
Parsing and validating a JWT from a JSON Web Key Set (JWKS).
I made this package to work with github.com/dgrijalva/jwt-go to more easily parse and validate JWTs with the most popular package.
Using your example URL, my_url, here's an example of how to parse and validate JWTs.
package main
import (
"log"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/MicahParks/keyfunc"
)
func main() {
// Get the JWKS URL.
jwksURL := "my_url"
// Create the keyfunc options. Refresh the JWKS every hour and log errors.
refreshInterval := time.Hour
options := keyfunc.Options{
RefreshInterval: &refreshInterval,
RefreshErrorHandler: func(err error) {
log.Printf("There was an error with the jwt.KeyFunc\nError: %s", err.Error())
},
}
// Create the JWKS from the resource at the given URL.
jwks, err := keyfunc.Get(jwksURL, options)
if err != nil {
log.Fatalf("Failed to create JWKS from resource at the given URL.\nError: %s", err.Error())
}
// Get a JWT to parse.
jwtB64 := "eyJhbGciOiJQUzM4NCIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJMeDFGbWF5UDJZQnR4YXFTMVNLSlJKR2lYUktudzJvdjVXbVlJTUctQkxFIn0.eyJleHAiOjE2MTU0MDY5ODIsImlhdCI6MTYxNTQwNjkyMiwianRpIjoiMGY2NGJjYTktYjU4OC00MWFhLWFkNDEtMmFmZDM2OGRmNTFkIiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwL2F1dGgvcmVhbG1zL21hc3RlciIsImF1ZCI6ImFjY291bnQiLCJzdWIiOiJhZDEyOGRmMS0xMTQwLTRlNGMtYjA5Ny1hY2RjZTcwNWJkOWIiLCJ0eXAiOiJCZWFyZXIiLCJhenAiOiJ0b2tlbmRlbG1lIiwiYWNyIjoiMSIsInJlYWxtX2FjY2VzcyI6eyJyb2xlcyI6WyJvZmZsaW5lX2FjY2VzcyIsInVtYV9hdXRob3JpemF0aW9uIl19LCJyZXNvdXJjZV9hY2Nlc3MiOnsiYWNjb3VudCI6eyJyb2xlcyI6WyJtYW5hZ2UtYWNjb3VudCIsIm1hbmFnZS1hY2NvdW50LWxpbmtzIiwidmlldy1wcm9maWxlIl19fSwic2NvcGUiOiJlbWFpbCBwcm9maWxlIiwiY2xpZW50SG9zdCI6IjE3Mi4yMC4wLjEiLCJjbGllbnRJZCI6InRva2VuZGVsbWUiLCJlbWFpbF92ZXJpZmllZCI6ZmFsc2UsInByZWZlcnJlZF91c2VybmFtZSI6InNlcnZpY2UtYWNjb3VudC10b2tlbmRlbG1lIiwiY2xpZW50QWRkcmVzcyI6IjE3Mi4yMC4wLjEifQ.Rxrq41AxbWKIQHWv-Tkb7rqwel3sKT_R_AGvn9mPIHqhw1m7nsQWcL9t2a_8MI2hCwgWtYdgTF1xxBNmb2IW3CZkML5nGfcRrFvNaBHd3UQEqbFKZgnIX29h5VoxekyiwFaGD-0RXL83jF7k39hytEzTatwoVjZ-frga0KFl-nLce3OwncRXVCGmxoFzUsyu9TQFS2Mm_p0AMX1y1MAX1JmLC3WFhH3BohhRqpzBtjSfs_f46nE1-HKjqZ1ERrAc2fmiVJjmG7sT702JRuuzrgUpHlMy2juBG4DkVcMlj4neJUmCD1vZyZBRggfaIxNkwUhHtmS2Cp9tOcwNu47tSg"
// Parse the JWT.
token, err := jwt.Parse(jwtB64, jwks.KeyFunc)
if err != nil {
log.Fatalf("Failed to parse the JWT.\nError: %s", err.Error())
}
// Check if the token is valid.
if !token.Valid {
log.Fatalf("The token is not valid.")
}
log.Println("The token is valid.")
}
As the title says, I have a JSON file generated based on https://mkjwk.org/ and now I want to use the generated values to sign a JWT. I will do this for multiple "clients", each with its own signature.
These will then be verified against a set of JWKS containing the public keys for the different "clients".
However, I'm struggling to understand how to use the generated JSON values..
I know I can generate one priv/pub keys directly with the crypto/rsa module. I've also seen examples where the ppk is given as input in X509 format, though I was trying to avoid it if possible (I guess I'm just being picky as I prefer to be able to read the contents of a file rather than seeing random chars..)
From the multiple examples and numerous searches I've done, I haven't seen one where the process of taking a json file and generating a rsa.privateKey is performed.
I'm also using the jwt-go and jwx modules to handle the rest of the use cases, but this one is escaping me..
So, what am I missing? How can I go from a JSON like the one below to a rsa.PrivateKey?
{
"p": "vQXloZI9y5..._PPE6m05J-VqhIF6-FQjvwc",
"kty": "RSA",
"q": "u1OqnCCLyEZDMoSfK...SfcIGNSd90PEcPs",
"d": "eoAj0Z0PkK3A0pc5t...9Q8iqGntoxMVARBtQ",
"e": "AQAB",
"use": "sig",
"kid": "r9cuFC3...HiAc7VhSME",
"qi": "upOjfCF_na...H4a7Bs2pWGoS6w5mcqXU",
"dp": "HKGzCclEEP...GdofDVR5Yas",
"alg": "RS256",
"dq": "PDyRNhc5G7OMVChVTm61kn2ShRFTe...BLytOxGBm5ntJv4V0HRBU",
"n": "ilEVn6tSuh7-tZBV8qXmlvzWDE5jTS...sNH8-wPf6gKCuZzEyyS2AyZE8S4NzqoFkaepVpdoOPtb3Q"
}
Thanks
The jwx package has a function to parse a JWK:
func ParseString(s string)
You can use it to parse the JWK like this, and use the key to sign and verify a JWT (pay attention to the code comments for further details):
package main
import(
"log"
"github.com/lestrrat-go/jwx/jwk"
"github.com/lestrrat-go/jwx/jws"
"github.com/lestrrat-go/jwx/jwa"
)
func main() {
// Here's an example of a JWK, containing a public and private RSA Keypair
var keysJWK = `{
"keys": [
{
"p": "59pSssPVWNBMd1dFBhkSx0P6uo3b3WC2MOitj7UI-9VS9gKPbPsqtDJSPdbRjK7JWXarFt_h4aPf9NPFLieu1k22jp3ProCH87geazJ8tNtV_SpaUtWQFZ-dvgGrIM-3MLf_fG7Tq5sV5R0vA9wg_INkYJ2uX5EdmVyHhxvh0eM",
"kty": "RSA",
"q": "jeofLDkteXfWcpif3JmX3xv8S6jWX2Axrwe9tLkWzlgxYDWvXExxD0sc4XfbVbSrqTkAdW48DYL_wcziFLYHxOYv2stqWvElF9CqdKJJrQAc7Z_qKXpWckDYZBJAO9W2WGXTBfdJfw_KQPHHTbY90ngdxMXuiwYbfbFY4H_XDM0",
"d": "Qrx8U40tLhsy4tdnKuEmjlGF-VkB6F_DawLXwuZ2a5ZS7cwFUDRHNz9Jbl9MxvNcNMSMGaAN8lxTSDlpfT0jDqKF6lel88rUtCnN6h1FNdkD5TjkbWs-dfhftDFc1Sy8RdWPZ8LiTo0TbZaf3rPvdLw_S9FE-itnKV_1il572rT-1PvlyrPctnREQCKL5wArD4eYHwRjfVm-KvlIvo9rLj4NYzATBAAwh6PsEnSganEf1ErOvFH8qhrVqsy2kevLsFbCA0hIfoDNhL7hxlaMSJTJie3V2Ie0Kb7j_L2LsQXka3kshO1T6re-d-nGgaRp7b0buUtwS6aTax0H2cZuOQ",
"e": "AQAB",
"use": "sig",
"kid": "223",
"qi": "moGHNM3TFLeSQeM6V4izMcK6wwapSwo67r7DXk7vK_2FaSUQtijwQCHFx3nrhbQAVdwFt7pSYlmlFPlaAXixrBBNtNULnR7z6-WrRuWgqoL9LN8xARB42l94HmiOL0pp8ORyw2W338k3LHuzUy1NKZrL6a8zPIkva_Z5hFULhQE",
"dp": "TcUm3j3gL3VXYOSOC5iXeu2ria4R5PUOx-MUbNLd25NXy5taPsUVMvJ6MbIAAj-S3IZ4pyib3RMaCUaLqoq3E71nkfkPc8o7UB4fXffGaufztQLi30wxk39B6z0mCNCD8zyU30lRiQtxUbPzVEkfa3QrVFkv53CGzC2EbGaG3d8",
"alg": "RS256",
"dq": "L1emNJOShw4iXTJrSiV3E7f7T6YwdbraeECF2c9RO18Sgb0HFixuHyL4rILWid3u0lIww_wVTpCgD5_w3-Xl65q65iur_FCsBijXZHdrSqpZ_C-350RnqE_XoHKyOQPPg-fcIQZg32F-IHJIAbXFI_xsOeOp83kDHMhYFPSw4hU",
"n": "gIdJV4qWKyt3wkS66yBG5Ii9ew-eofuPU49TjlRIU5Iu5jX2mRMoHdcI7V78iKYSQHKYxz17cqzQyERxKnEiDgy_gwouStRgvPdm3H4rq__7p0t15SunsG2T1rEVf0sZEDnQ5qRkm7iqs6ZG1NqqIUtnOTd1Pd1MhbEqeENFtaPHvN37eZL82WmsQlJviFH4I9iZQVR_QT4GREQlRro8IjJTaloUyeDQTOQ-4ll1-4-g_ug2tZ-s9xleLzl5L9ZKSVJFhtMLn8WGaVldagarwa7kMLfuiVe8B5Lr7poQa4NCAR54ECPWoOHrABdPZKrkkxjVypTXUzL5cPzmzFC2xw"
}
]
}`
// Parse the JWK to a set of keys
setOfKeys, err := jwk.ParseString(keysJWK )
if err != nil {
log.Printf("failed to parse JWK: %s", err)
return
}
// extract the private key from the set, index 0 because w only have one key
rsaPrivatekey, success := setOfKeys.Get(0)
if !success {
log.Printf("could not find key at given index")
return
}
// sign a token with the private key
token, err := jws.Sign([]byte(`{"userId":1}`), jwa.RS256, rsaPrivatekey)
if err != nil {
log.Printf("failed to created JWS message: %s", err)
return
}
// show the signed token
log.Printf("Token! -> %s", token)
// get a public key from a private key
rsaPublicKey, err := jwk.PublicKeyOf(rsaPrivatekey)
if err != nil {
log.Printf("failed created public key from private key: %s", err)
return
}
// verify the token that we created above with the public key
payload, err := jws.Verify(token, jwa.RS256, rsaPublicKey)
if err != nil {
log.Printf("failed to verify message: %s", err)
return
}
// show the payload of the verified token
log.Printf("signature verified! Payload -> %s", payload)
}
try it on the Go Playground
I have a code # http://play.golang.org/p/HDlJJ54YqW
I wanted to print the Phone and email of a person.
It can be of multiple entries.
But getting the error undefined.
Can anyone help out.
Thanks.
Small details: you are referencing twice: you give the address of the address of the object to json.Unmarshal. Just give the address.
` allows for multiline, no need to split your json input.
I don't know what you where trying to achieve with u.Details[Phone:"1111"].Email, but this is no Go syntax. your Details member is a slice off Detail. A slice is similar to an array and can be accessed by index.
Also, your json does not match your object structure. If you want to have multiple details in one content, then it needs to be embed in an array ([ ])
You could do something like this: (http://play.golang.org/p/OP1zbPW_wk)
package main
import (
"encoding/json"
"fmt"
)
type Content struct {
Owner string
Details []*Detail
}
type Detail struct {
Phone string
Email string
}
func (c *Content) SearchPhone(phone string) *Detail {
for _, elem := range c.Details {
if elem.Phone == phone {
return elem
}
}
return nil
}
func (c *Content) SearchEmail(email string) *Detail {
for _, elem := range c.Details {
if elem.Email == email {
return elem
}
}
return nil
}
func main() {
encoded := `{
"Owner": "abc",
"Details": [
{
"Phone": "1111",
"Email": "#gmail"
},
{
"Phone": "2222",
"Email": "#yahoo"
}
]
}`
// Decode the json object
u := &Content{}
if err := json.Unmarshal([]byte(encoded), u); err != nil {
panic(err)
}
// Print out Email and Phone
fmt.Printf("Email: %s\n", u.SearchPhone("1111").Email)
fmt.Printf("Phone: %s\n", u.SearchEmail("#yahoo").Phone)
}