Go语言 如何将RSA公钥转换为JSON Web Key

kokeuurv  于 2023-08-01  发布在  Go
关注(0)|答案(2)|浏览(107)

我有一个pem格式的RSA公钥,我想把它转换成JSON Web Key。
RSA:

-----BEGIN PUBLIC KEY-----

 MIGfMA0GCSqGSIb3DQEBAQUBB4GNADCBiQKBgQCqGKukO1De7zhZj6+H0qtjTkVxwTCpvKe4eCZ0
 FPqri0cb2JZfXJ/DgYSF6vUpwmJG8wVQZKjeGcjDOL5UlsuusFncCzWBQ7RKNUSesmQRMSGkVb1/
 3j+skZ6UtW+5u09lHNsj6tQ51s1SPrCBkedbNf0Tp0GbMJDyR4e9T04ZZwIDAQAB

-----END PUBLIC KEY-----

字符串
JWK:

{"keys":[{"kty":"RSA","kid":"201","use":"sig","alg":"RS256","n":"gslsSwlsweQKOG5sHLJEZ8-
_cWBTiMhuEc59ETC1raGKRmjYcp2UQulzyHC5it30JEfITQGScDeRefNw9pdsG2CEM0wBqji8ib_HEbVm1JjQZNqHxv4
2I6LeK2O2qaDcePcM9DlpAuprnJndhElk0NuRO_Q6vl8WQT7g1TlSxLWxcUgyuK8YmYNThgSkX9Y47oCDX3bFkH60YG6c4IcWHJPRKb
X5rgnTe8hGflfR3k","e":"AQAB"}]}


我找不到一种方法在Go中成功地做到这一点。

vxbzzdmp

vxbzzdmp1#

这是:

pubKey, err := ioutil.ReadFile("pathToPublicKey")
    if err != nil {
        log.Printf("key not found", err)
        return err
    }

    pubPem, _ := pem.Decode(pubKey)

    pub, _ := x509.ParsePKCS1PrivateKey(pubPem.Bytes)

    set, err := jwk.New(pub)
    if err != nil {
        log.Printf("failed to convert to JWK: %s", err)
        return err
    }

    err = jwk.AssignKeyID(set)
    if err != nil {
        log.Printf("failed to assign kid: %s", err)
        return err
    }

字符串
我使用了这个包:godoc.org/github.com/lestrrat/go-jwx/jwk

oyt4ldly

oyt4ldly2#

使用其他常用库的解决方案。加载publicKey字节,无论你想要的,例如从文件、Vault等...在jose.JSONWebKeySet上使用json.Marshal获取JSON响应。

package auth

import (
    "github.com/go-jose/go-jose/v3"
    "github.com/golang-jwt/jwt/v4"
)

type JwkProvider interface {
    Provide() (*jose.JSONWebKeySet, error)
}

type rsaJwkProvider struct {
    keyID     string
    publicKey []byte
}

func NewRsaJwkProvider(keyID string, publicKey []byte) JwkProvider {
    return &rsaJwkProvider{keyID: keyID, publicKey: publicKey}
}

func (p *rsaJwkProvider) Provide() (*jose.JSONWebKeySet, error) {
    rsaPublicKey, err := jwt.ParseRSAPublicKeyFromPEM(p.publicKey)
    if err != nil {
        return nil, err
    }
    jsonWebKey := jose.JSONWebKey{
        Key:       rsaPublicKey,
        KeyID:     p.keyID,
        Algorithm: "RS256",
        Use:       "sig",
    }
    return &jose.JSONWebKeySet{Keys: []jose.JSONWebKey{jsonWebKey}}, nil
}

字符串

相关问题