gmjwt

module
v1.0.0-beta.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 25, 2025 License: MIT

README

GMJWT开发文档

简介

这是 gmjwt 模块的开发文档,提供基于国密算法的 JWT 签名支持,目前包含:

  • SM2:基于 SM2 签名(内部使用 SM3 计算摘要并进行 SM2 签名/验证)。
  • HSM3:基于 SM3 的 HMAC 签名(用作对称密钥签名)。

模块在包下的实现文件:

  • sm2:实现 SM2 签名方法及 DER<->RS 的转换(见 sm2/der.go)。
  • hsm3:实现 HSM3(基于 HMAC-SM3)。

快速开始 / 用法示例

通用说明:本库通过 github.com/golang-jwt/jwt/v5 注册自定义签名方法,注册的算法名字为 SM2HSM3,可直接使用 jwt.GetSigningMethod("SM2")jwt.GetSigningMethod("HSM3") 创建 token。

  • 使用 SM2 签名(假设已有 *sm2.PrivateKey*sm2.PublicKey):
import (
    _ "github.com/KindLittleTurtle/gmjwt/sm2"
    "github.com/golang-jwt/jwt/v5"
    "github.com/tjfoc/gmsm/sm2"
)

// 创建并签名
token := jwt.NewWithClaims(jwt.GetSigningMethod("SM2"), jwt.MapClaims{"sub": "alice"})
signed, err := token.SignedString(mySM2PrivateKey) // mySM2PrivateKey: *sm2.PrivateKey

// 验证
parsed, err := jwt.ParseWithClaims(signed, jwt.MapClaims{}, func(t *jwt.Token) (interface{}, error) {
    return &mySM2PublicKey, nil // mySM2PublicKey: sm2.PublicKey (或 *sm2.PublicKey)
})

注意:为了携带自定义 UID,可以使用封装类型 SM2PrivateKey / SM2PublicKey(参见 sm2/jwt.go),格式为:

type SM2PrivateKey struct {
    Key *sm2.PrivateKey
    UID []byte
}

type SM2PublicKey struct {
    Key *sm2.PublicKey
    UID []byte
}
  • 使用 HSM3(对称 HMAC-SM3):
import (
    _ "github.com/KindLittleTurtle/gmjwt/hsm3"
    "github.com/golang-jwt/jwt/v5"
)
token := jwt.NewWithClaims(jwt.GetSigningMethod("HSM3"), jwt.MapClaims{"sub": "bob"})
signed, err := token.SignedString([]byte("your-secret-key"))

parsed, err := jwt.ParseWithClaims(signed, jwt.MapClaims{}, func(t *jwt.Token) (interface{}, error) {
    return []byte("your-secret-key"), nil
})

代码细节与注意事项

  • SM2 实现使用 sm3.Sm3Sum 对消息摘要后调用 sm2.Sm2Sign/sm2.Sm2Verify,签名在库内做了 RS <-> DER 的转换(参见 sm2/der.go)。
  • HSM3 实现使用 crypto/hmacgithub.com/tjfoc/gmsm/sm3 做 HMAC-SM3。签名/验证函数接受 string[]byte 类型的密钥(参见 hsm3/jwt.go)。
  • 默认 UID 为 "1234567812345678"(当 UID 字段为 nil 时使用)。

依赖

主要依赖已在 go.mod 中声明:

  • github.com/golang-jwt/jwt/v5(用于 JWT 核心逻辑)
  • github.com/tjfoc/gmsm(包含 sm2, sm3 实现)

(详见 go.mod

许可

本项目源码头部声明采用 MIT 许可证。详见源码文件顶部的许可声明。

贡献

欢迎提交 issue 或 PR。建议在 PR 中包含可复现的测试用例或使用示例。

Directories

Path Synopsis
MIT License
MIT License
MIT License
MIT License

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL