Search code examples
gojwtrsajwk

Convert a JSON Public/Private Key pair to rsa.PrivateKey and rsa.PublicKey


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


Solution

  • 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