1

I'm trying to generate a pem string using github.com/lestrrat-go/jwx/jwk.

But so far I coudn't, I'm guessing it's because I'm new to go and there's something I'm not understanding. I have gone through the relevant examples of this library.

My code fetchs a JWK from a server, once I have it, I try to generate a pem string here :

// validationCrt contains my []byte from the server
set, err := jwk.Parse(validationCrt)
if err != nil {
    println(err)
}

// I suspect this piece of code is actually a mess
// but I just can't understand what I'm doing wrong
key, err := jwk.GetPublicKey(set)
if err != nil {
    log.Printf("failed to create public key: %s", err)
}

I am really lost I tried multiple ways (with and without this lib) and it seems I can't find any example out there (they usually explain how to generate a key, or go from pem to jwt, but my Go app is a client.)

blackgreen
  • 34,072
  • 23
  • 111
  • 129
Russo
  • 301
  • 3
  • 12
  • 1
    From the docs it looks like [the Materialize method](https://godoc.org/github.com/lestrrat-go/jwx/jwk#Key) returns the corresponding type from the standard library. You should be able to find examples for how to marshal *those* into PEM using the [x509](https://golang.org/pkg/crypto/x509/) and [pem](https://golang.org/pkg/encoding/pem/) packages. – Peter Apr 09 '19 at 06:24
  • 1
    Thanks @Peter ! Thanks to your comment I found a question I didn't see before here : https://stackoverflow.com/questions/41077953/go-language-and-verify-jwt I had to refactor my code because I was trying to achieve this with another lib. – Russo Apr 09 '19 at 23:24

1 Answers1

2

Authorization server usually provides an endpoint to obtain JSON Web Keyset (JWKS). So I think validationCrt would indeed be a JSON Web Keyset. Nevertheless, you can json.Unmarshal() to JWK/JWKS (square/go-jose) and obtain the reference of the public key via .Key.

Getting to PEM format is as simple as

...
pubData, err := x509.MarshalPKIXPublicKey(pubKey)
if err != nil {
    return err
}
if err := pem.Encode(os.Stdout, &pem.Block{
    Type:  "PUBLIC KEY",
    Bytes: pubData,
}); err != nil {
    return err
}
...
trung
  • 1,104
  • 11
  • 13