dpdjpt5137 2015-03-20 02:57
浏览 909

带有rsa密钥的Golang软件包jwt-go。 如何放置公钥以及如何从令牌中获取公钥?

I'm trying to generate a token with a rsa key using the jwt-go package in golang. Here there is a blog explaining how to do it but that code will always be validating all tokens because is using the public key stored in the server and is not obtaining it from the token. How do you put the complete public key in the token? I was trying this:

var secretKey, _ = rsa.GenerateKey(rand.Reader, 1024)
token := jwt.New(jwt.SigningMethodRS256)
token.Claims["username"] = "victorsamuelmd"
token.Claims["N"] = secretKey.PublicKey.N
token.Claims["E"] = secretKey.PublicKey.E

tokenString, err := token.SignedString(secretKey)

nt, err := jwt.Parse(tokenString, func(t *jwt.Token) (interface{}, error) {
    // here I need to recover the public key from the token
    // but N is a big.Int and the token stores N as int64
})

Sorry about my english. Thanks.

  • 写回答

1条回答 默认 最新

  • dongpi3237 2017-07-27 14:59
    关注

    I think storing the public key in the claims is not good idea because we can verify the JWT with that key technically, but it means it is not a signed JWT anymore. If anyone can generate the JWT with their own private key and storing the public key in JWT, we cannot sure who is signer.

    Anyway, you can convert the public key into PEM format which is just a string, and store it in claims. In client side, you can also simply parse it again into public key format. The sample code is below:

    privateKey, _ := rsa.GenerateKey(rand.Reader, 1024)
    bytes, _ := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)
    pem := pem.EncodeToMemory(&pem.Block{
        Type:  "RSA PUBLIC KEY",
        Bytes: bytes,
    })
    claim["publickey"] = string(pem)
    

    and

    pem := []byte(claims["publickey"].(string))
    return jwt.ParseRSAPublicKeyFromPEM(pem)
    

    jwt is dgrijalva's jwt-go.

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!