Files
ssw-mvp/scard/code/common/crypto/sm2.go
T
admin 3247e9fd15 init: ssw-mvp initial commit
- boot/ (Java/Maven, JNPF 7.0) — 移除旧的 boot/.git,源码直接纳入仓库
- web/ (Vue 3 + Vite + Ant Design Vue, pnpm)
- docs/, scard/, nax/
- refs/INDEX.md + refs/国标/(其余 refs/* 开源子仓库不纳入)
- 已忽略: connector_data/, jweb/, log/, web/{dist,node_modules,.pnpm}, boot/*/target/, .DS_Store, .idea, .vscode
2026-08-05 18:29:12 +08:00

384 lines
9.8 KiB
Go

// SM2 public key cryptography
// Reference: GB/T 32918.2-2016, GB/T 32918.3-2016, GM/T 0003-2012
// Includes:
// - SM2 key pair generation
// - SM2 ECDH key exchange
// - SM2 digital signature
package crypto
import (
"crypto"
"crypto/rand"
"errors"
"io"
"math/big"
)
var (
// SM2UserID is the default user identifier used when computing ZA.
//
// GB/T 32918.2-2016 fixes the default as the 16-byte ASCII string
// "1234567812345678" (ENTL = 0x0080). A shorter ID yields a different ZA
// and therefore signatures that no conformant implementation can verify.
SM2UserID = []byte("1234567812345678")
)
// SM2PublicKey represents an SM2 public key
type SM2PublicKey struct {
CurveParams SM2Params
X, Y *big.Int
}
// SM2PrivateKey represents an SM2 private key
type SM2PrivateKey struct {
PublicKey *SM2PublicKey
D *big.Int
}
// Public returns the public key
func (priv *SM2PrivateKey) Public() crypto.PublicKey {
return priv.PublicKey
}
// Sign signs data using SM2
func (priv *SM2PrivateKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
return SM2Sign(priv, digest)
}
// GenerateSM2Key generates a new SM2 key pair
func GenerateSM2Key() (*SM2PrivateKey, error) {
if SM2P256V1Params == nil {
return nil, errors.New("SM2: curve not available")
}
key := new(SM2PrivateKey)
var err error
key.D, err = randFieldElement(SM2P256V1Params, rand.Reader)
if err != nil {
return nil, err
}
key.PublicKey = &SM2PublicKey{CurveParams: *SM2P256V1Params}
// Compute public key: Q = d*G
gx, gy := SM2P256V1Params.Gx, SM2P256V1Params.Gy
key.PublicKey.X, key.PublicKey.Y = SM2P256V1.ScalarMult(gx, gy, key.D.Bytes())
return key, nil
}
// randFieldElement returns a random element of the field
func randFieldElement(params *SM2Params, rand io.Reader) (*big.Int, error) {
// Get the order n of the curve
n := params.N
if n.Sign() == 0 {
return nil, errors.New("SM2: invalid curve order")
}
// Generate random bytes
bitSize := n.BitLen()
bytes := make([]byte, (bitSize+7)/8)
_, err := io.ReadFull(rand, bytes)
if err != nil {
return nil, err
}
// Reduce mod n
result := new(big.Int).SetBytes(bytes)
result.Mod(result, n)
// Handle zero case
if result.Sign() == 0 {
return randFieldElement(params, rand)
}
return result, nil
}
// SM2Sign signs a message using SM2 (GB/T 32918.2-2016, clause 6.1).
//
// Signature generation:
//
// ZA = SM3(ENTL || ID || a || b || xG || yG || xA || yA)
// e = SM3(ZA || M)
// k <- [1, n-1]
// (x1, y1) = [k]G
// r = (e + x1) mod n , retry if r == 0 or r + k == n
// s = ((1 + dA)^-1 * (k - r*dA)) mod n , retry if s == 0
//
// The returned signature is the fixed-width big-endian concatenation r || s (64 bytes).
func SM2Sign(priv *SM2PrivateKey, msg []byte) ([]byte, error) {
if priv == nil || priv.D == nil || priv.PublicKey == nil {
return nil, errors.New("SM2: invalid private key")
}
curve := SM2P256V1
n := SM2P256V1Params.N
// ZA binds the signer identity and public key into the digest.
za := SM2ComputeZA(&priv.PublicKey.CurveParams, SM2UserID, priv.PublicKey.X, priv.PublicKey.Y)
e := hashDigits(za, msg)
// (1 + dA)^-1 mod n is independent of k, compute it once.
onePlusD := new(big.Int).Add(big.NewInt(1), priv.D)
onePlusD.Mod(onePlusD, n)
onePlusDInv := modInverse(onePlusD, n)
if onePlusDInv == nil {
return nil, errors.New("SM2: private key has no (1+d) inverse")
}
for attempt := 0; attempt < 256; attempt++ {
k, err := randFieldElement(SM2P256V1Params, rand.Reader)
if err != nil {
return nil, err
}
if k.Sign() == 0 || k.Cmp(n) >= 0 {
continue
}
// (x1, y1) = [k]G
x1, _ := curve.ScalarBaseMult(k.Bytes())
// r = (e + x1) mod n
r := new(big.Int).Add(e, x1)
r.Mod(r, n)
if r.Sign() == 0 {
continue
}
// r + k == n is forbidden by the standard.
if new(big.Int).Add(r, k).Cmp(n) == 0 {
continue
}
// s = ((1 + dA)^-1 * (k - r*dA)) mod n
rd := new(big.Int).Mul(r, priv.D)
rd.Mod(rd, n)
s := new(big.Int).Sub(k, rd)
s.Mod(s, n) // big.Int Mod always returns a non-negative result for positive n
s.Mul(s, onePlusDInv)
s.Mod(s, n)
if s.Sign() == 0 {
continue
}
// Return r || s
result := make([]byte, 64)
copy(result[:32], padBytes(r.Bytes(), 32))
copy(result[32:], padBytes(s.Bytes(), 32))
return result, nil
}
return nil, errors.New("SM2: failed to produce a signature after 256 attempts")
}
// SM2Verify verifies an SM2 signature (GB/T 32918.2-2016, clause 7.1).
//
// e = SM3(ZA || M)
// t = (r + s) mod n , reject if t == 0
// (x1, y1) = [s]G + [t]PA
// accept iff (e + x1) mod n == r
func SM2Verify(pub *SM2PublicKey, msg []byte, sig []byte) bool {
if pub == nil || pub.X == nil || pub.Y == nil {
return false
}
if len(sig) != 64 {
return false
}
// Parse r and s
r := new(big.Int).SetBytes(sig[:32])
s := new(big.Int).SetBytes(sig[32:])
n := pub.CurveParams.N
if n == nil || n.Sign() == 0 {
return false
}
if r.Sign() <= 0 || r.Cmp(n) >= 0 {
return false
}
if s.Sign() <= 0 || s.Cmp(n) >= 0 {
return false
}
// ZA = SM3(ENTL || ID || a || b || xG || yG || xA || yA)
za := SM2ComputeZA(&pub.CurveParams, SM2UserID, pub.X, pub.Y)
// e = SM3(ZA || M)
e := hashDigits(za, msg)
// t = (r + s) mod n
t := new(big.Int).Add(r, s)
t.Mod(t, n)
if t.Sign() == 0 {
return false
}
// (x1, y1) = [s]G + [t]PA
curve := SM2P256V1
sGx, sGy := curve.ScalarBaseMult(padBytes(s.Bytes(), 32))
tPx, tPy := curve.ScalarMult(pub.X, pub.Y, padBytes(t.Bytes(), 32))
x1, y1 := curve.Add(sGx, sGy, tPx, tPy)
if x1.Sign() == 0 && y1.Sign() == 0 {
// point at infinity
return false
}
// v = (e + x1) mod n must equal r
v := new(big.Int).Add(e, x1)
v.Mod(v, n)
return v.Cmp(r) == 0
}
// SM2ECDH performs ECDH key exchange
func SM2ECDH(privateKey *SM2PrivateKey, publicKey *SM2PublicKey) ([]byte, error) {
// Compute shared point
curve := SM2P256V1
x, _ := curve.ScalarMult(publicKey.X, publicKey.Y, privateKey.D.Bytes())
if x.Sign() == 0 {
return nil, errors.New("SM2 ECDH: shared point is at infinity")
}
// Use x coordinate as shared secret (fixed 32-byte big-endian, so that a
// leading zero byte cannot change the derived key)
shared, err := DeriveKey(padBytes(x.Bytes(), 32), nil, HKDFInfoKEK, AES256KeySize)
if err != nil {
return nil, err
}
return shared, nil
}
// SM2ComputeZA computes ZA = SM3(ENTL || ID || a || b || xG || yG || xA || yA)
// as defined by GB/T 32918.2-2016 clause 5.5.
//
// ENTL is the *bit* length of ID encoded as a 2-byte big-endian integer, and
// xA/yA are the signer public key coordinates. Omitting xA/yA (or encoding
// ENTL as a byte length) yields a non-conformant ZA that will not interoperate
// with any standard SM2 implementation.
func SM2ComputeZA(params *SM2Params, id []byte, pubX, pubY *big.Int) []byte {
h := NewSM3()
// ENTL: bit length of ID, 2 bytes big-endian
entl := len(id) * 8
h.Write([]byte{byte(entl >> 8), byte(entl)})
// ID
h.Write(id)
// a, b (32 bytes each, big-endian)
h.Write(padBytes(params.A.Bytes(), 32))
h.Write(padBytes(params.B.Bytes(), 32))
// xG, yG (32 bytes each, big-endian)
h.Write(padBytes(params.Gx.Bytes(), 32))
h.Write(padBytes(params.Gy.Bytes(), 32))
// xA, yA (32 bytes each, big-endian) - the signer public key
if pubX != nil {
h.Write(padBytes(pubX.Bytes(), 32))
} else {
h.Write(make([]byte, 32))
}
if pubY != nil {
h.Write(padBytes(pubY.Bytes(), 32))
} else {
h.Write(make([]byte, 32))
}
return h.Sum(nil)
}
func hashDigits(za, msg []byte) *big.Int {
h := NewSM3()
h.Write(za)
h.Write(msg)
return new(big.Int).SetBytes(h.Sum(nil))
}
func padBytes(b []byte, length int) []byte {
if len(b) >= length {
return b[len(b)-length:]
}
result := make([]byte, length)
copy(result[length-len(b):], b)
return result
}
func modInverse(a, m *big.Int) *big.Int {
// Use the built-in ModInverse (Go 1.15+)
result := new(big.Int)
inv := result.ModInverse(a, m)
if inv == nil {
return nil
}
return inv
}
// Sm2KeyExchange performs SM2 key exchange
// Returns session key material
func Sm2KeyExchange(privateKey *SM2PrivateKey, peerPublicKey *SM2PublicKey, role string) ([]byte, error) {
// Derive shared secret via ECDH
sharedSecret, err := SM2ECDH(privateKey, peerPublicKey)
if err != nil {
return nil, err
}
// Derive session keys using SM3-based HKDF
derived, err := DeriveKey(sharedSecret, []byte(role), "SM2-KeyExchange", AES256KeySize)
if err != nil {
return nil, err
}
return derived, nil
}
// EncodeSM2PublicKey encodes an SM2 public key to bytes
func EncodeSM2PublicKey(pub *SM2PublicKey) ([]byte, error) {
xBytes := padBytes(pub.X.Bytes(), 32)
yBytes := padBytes(pub.Y.Bytes(), 32)
return append(xBytes, yBytes...), nil
}
// ParseSM2PublicKey parses an SM2 public key from bytes
func ParseSM2PublicKey(data []byte) (*SM2PublicKey, error) {
if len(data) != 64 {
return nil, errors.New("SM2: invalid public key length")
}
pub := &SM2PublicKey{
CurveParams: *SM2P256V1Params,
}
pub.X = new(big.Int).SetBytes(data[:32])
pub.Y = new(big.Int).SetBytes(data[32:])
// Verify point is on curve
if !SM2P256V1.IsOnCurve(pub.X, pub.Y) {
return nil, errors.New("SM2: point not on curve")
}
return pub, nil
}
// EncodeSM2PrivateKey encodes an SM2 private key to bytes
func EncodeSM2PrivateKey(priv *SM2PrivateKey) []byte {
return padBytes(priv.D.Bytes(), 32)
}
// ParseSM2PrivateKey parses an SM2 private key from bytes
func ParseSM2PrivateKey(data []byte) (*SM2PrivateKey, error) {
if len(data) != 32 {
return nil, errors.New("SM2: invalid private key length")
}
d := new(big.Int).SetBytes(data)
if d.Sign() <= 0 || d.Cmp(SM2P256V1Params.N) >= 0 {
return nil, errors.New("SM2: private key out of range [1, n-1]")
}
priv := &SM2PrivateKey{D: d}
priv.PublicKey = &SM2PublicKey{
CurveParams: *SM2P256V1Params,
}
priv.PublicKey.X, priv.PublicKey.Y = SM2P256V1.ScalarBaseMult(data)
return priv, nil
}