Golang包jwt-go用rsa键。如何设置公钥以及如何从令牌中获取公钥?

时间:2015-03-20 02:57:42

标签: go cryptography rsa jwt

我尝试使用golang中的jwt-go包生成带有rsa密钥的令牌。 Here有一个博客解释了如何做,但该代码将始终验证所有令牌,因为它使用存储在服务器中的公钥,而不是从令牌获取它。如何将完整的公钥放在令牌中?我正在尝试这个:

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
})

抱歉我的英语。感谢。

1 个答案:

答案 0 :(得分:2)

我认为将公钥存储在声明中并不是一个好主意,因为我们可以在技术上用该密钥验证JWT,但这意味着它不再是已签名的JWT。如果任何人都可以使用自己的私钥生成JWT并将公钥存储在JWT中,我们无法确定谁是签名者。

无论如何,您可以将公钥转换为PEM格式,这只是一个字符串,并将其存储在声明中。在客户端,您还可以简单地将其再次解析为公钥格式。示例代码如下:

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)

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

jwtdgrijalva's jwt-go