根据您的意见,我汇总了一个可以帮助您解决问题的回复。首先,我使用了包的版本 2,gopkg.in/go-jose/go-jose.v2因为(据我所知)该算法A256GCM在最新版本的包中不完全兼容,应该是版本 3。您可以在下面找到相关代码:


package main


import (

    "crypto/rand"

    "crypto/rsa"

    "fmt"

    "io"

    "os"

    "time"


    "github.com/golang-jwt/jwt"

    jose_jwt "gopkg.in/go-jose/go-jose.v2"

)


type CustomClaims struct {

    Username string `json:"username"`

    Password string `json:"password"`

    jwt.StandardClaims

}


func main() {

    privateKey, err := rsa.GenerateKey(rand.Reader, 2048)

    if err != nil {

        panic(err)

    }


    // generate token

    token, err := generateToken()

    if err != nil {

        panic(err)

    }


    publicKey := &privateKey.PublicKey

    encrypter, err := jose_jwt.NewEncrypter(jose_jwt.A256GCM, jose_jwt.Recipient{

        Algorithm: jose_jwt.RSA_OAEP_256,

        Key:       publicKey,

    }, nil)

    if err != nil {

        panic(err)

    }


    plainText := []byte(token)

    object, err := encrypter.Encrypt(plainText)

    if err != nil {

        panic(err)

    }


    serialized := object.FullSerialize()


    object, err = jose_jwt.ParseEncrypted(serialized)

    if err != nil {

        panic(err)

    }


    decrypted, err := object.Decrypt(privateKey)

    if err != nil {

        panic(err)

    }


    fmt.Println(string(decrypted))


    // parse token

    claims, err := ValidateToken(string(decrypted))

    if err != nil {

        panic(err)

    }


    fmt.Println(len(claims))

}

在这里,我们首先生成一个私钥来加密令牌,然后通过它的公钥对其进行解密。为简洁起见,我省略了用于生成和验证 JWT 令牌的代码。为了测试解决方案,我向生成的令牌添加了两个自定义声明(username并且在结构password中定义CustomClaims)。然后,当我们解析令牌时,我们将能够检索它们的值。

让我知道这是否对您有帮助!