Files
ssw-mvp/scard/code/common/crypto/cipher_suite.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

402 lines
11 KiB
Go

// CipherSuite defines the interface for cryptographic algorithms
// This allows switching between international and GM cipher suites
package crypto
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"errors"
"hash"
)
// CipherSuiteType represents the type of cipher suite
type CipherSuiteType string
const (
CipherSuiteInternational CipherSuiteType = "international"
CipherSuiteGM CipherSuiteType = "gm"
)
// KeyExchangeResult holds the result of a key exchange operation
type KeyExchangeResult struct {
SharedSecret []byte
PublicKey []byte
PrivateKey []byte
EphemeralKey []byte // For ECDH schemes
}
// SignatureResult holds the result of a signing operation
type SignatureResult struct {
Signature []byte
PublicKey []byte
}
// CipherSuite interface defines the cryptographic operations
type CipherSuite interface {
// Key Generation
GenerateKeyPair() (interface{}, interface{}, error) // returns (privateKey, publicKey, error)
// Key Exchange
DeriveSharedSecret(privateKey, peerPublicKey interface{}) ([]byte, error)
// Signing
Sign(privateKey interface{}, message []byte) ([]byte, error)
Verify(publicKey interface{}, message, signature []byte) bool
// Symmetric Encryption
Encrypt(key, plaintext, aad []byte) ([]byte, error)
Decrypt(key, ciphertext, aad []byte) ([]byte, error)
// Hashing
Hash(data []byte) []byte
NewHash() hash.Hash
// Key Derivation
DeriveKey(salt, ikm []byte, info string, length int) ([]byte, error)
// Encoding helpers
EncodePublicKey(publicKey interface{}) ([]byte, error)
ParsePublicKey(data []byte) (interface{}, error)
// Suite identification
GetType() CipherSuiteType
String() string
}
// GMKeyExchangeResult holds SM2 key exchange results
type GMKeyExchangeResult struct {
SharedSecret []byte
KeKi []byte // Key encryption key material
SenderU []byte // Ephemeral public key U
}
// gmCipherSuite implements the GM cipher suite
type gmCipherSuite struct{}
// InternationalCipherSuite implements the international cipher suite
type internationalCipherSuite struct{}
var (
defaultGMCS = &gmCipherSuite{}
defaultInternationalCS = &internationalCipherSuite{}
currentCipherSuite CipherSuite = defaultInternationalCS
)
// SetCipherSuite sets the active cipher suite
func SetCipherSuite(suiteType CipherSuiteType) {
switch suiteType {
case CipherSuiteGM:
currentCipherSuite = defaultGMCS
default:
currentCipherSuite = defaultInternationalCS
}
}
// GetCipherSuite returns the current cipher suite
func GetCipherSuite() CipherSuite {
return currentCipherSuite
}
// GetCipherSuiteByType returns a cipher suite by type
func GetCipherSuiteByType(suiteType CipherSuiteType) CipherSuite {
switch suiteType {
case CipherSuiteGM:
return defaultGMCS
default:
return defaultInternationalCS
}
}
// GetType returns the cipher suite type
func (s *gmCipherSuite) GetType() CipherSuiteType {
return CipherSuiteGM
}
func (s *gmCipherSuite) String() string {
return "GM (SM2/SM3/SM4)"
}
func (s *internationalCipherSuite) GetType() CipherSuiteType {
return CipherSuiteInternational
}
func (s *internationalCipherSuite) String() string {
return "International (P-256/ECDSA/SHA-256)"
}
// GenerateKeyPair generates a key pair based on the cipher suite
func (s *gmCipherSuite) GenerateKeyPair() (interface{}, interface{}, error) {
priv, err := GenerateSM2Key()
if err != nil {
return nil, nil, err
}
return priv, priv.PublicKey, nil
}
func (s *internationalCipherSuite) GenerateKeyPair() (interface{}, interface{}, error) {
priv, err := GenerateECDSAKey()
if err != nil {
return nil, nil, err
}
return priv, &priv.PublicKey, nil
}
// DeriveSharedSecret derives a shared secret using ECDH
func (s *gmCipherSuite) DeriveSharedSecret(privateKey, peerPublicKey interface{}) ([]byte, error) {
priv, ok := privateKey.(*SM2PrivateKey)
if !ok {
return nil, ErrInvalidCurve
}
pub, ok := peerPublicKey.(*SM2PublicKey)
if !ok {
return nil, ErrInvalidCurve
}
return SM2ECDH(priv, pub)
}
func (s *internationalCipherSuite) DeriveSharedSecret(privateKey, peerPublicKey interface{}) ([]byte, error) {
priv, ok := privateKey.(*ecdsa.PrivateKey)
if !ok {
return nil, ErrInvalidCurve
}
pub, ok := peerPublicKey.(*ecdsa.PublicKey)
if !ok {
return nil, ErrInvalidCurve
}
return ECDH(priv, pub)
}
// Sign signs a message using the cipher suite's signature algorithm
func (s *gmCipherSuite) Sign(privateKey interface{}, message []byte) ([]byte, error) {
priv, ok := privateKey.(*SM2PrivateKey)
if !ok {
return nil, ErrInvalidCurve
}
// SM2Sign expects raw message and computes e = H(Za || M) internally
return SM2Sign(priv, message)
}
func (s *internationalCipherSuite) Sign(privateKey interface{}, message []byte) ([]byte, error) {
priv, ok := privateKey.(*ecdsa.PrivateKey)
if !ok {
return nil, ErrInvalidCurve
}
return Sign(priv, message)
}
// Verify verifies a signature
func (s *gmCipherSuite) Verify(publicKey interface{}, message, signature []byte) bool {
pub, ok := publicKey.(*SM2PublicKey)
if !ok {
return false
}
return SM2Verify(pub, message, signature)
}
func (s *internationalCipherSuite) Verify(publicKey interface{}, message, signature []byte) bool {
pub, ok := publicKey.(*ecdsa.PublicKey)
if !ok {
return false
}
return Verify(pub, message, signature)
}
// sm4KeyFrom normalises an arbitrary-length key material into a 16-byte SM4 key.
// A 16-byte key is used as-is; any other length (typically the 32-byte KEK/DEK
// used elsewhere in the system) is compressed with SM3 so that the GM suite is a
// drop-in replacement for the international suite.
func sm4KeyFrom(key []byte) ([]byte, error) {
switch {
case len(key) == SM4KeySize:
return key, nil
case len(key) == 0:
return nil, ErrInvalidKeySize
default:
return SM3(key)[:SM4KeySize], nil
}
}
// Encrypt encrypts data with SM4-GCM.
//
// A fresh random 96-bit nonce is generated for every call and prepended to the
// output: nonce || ciphertext || tag. Reusing a nonce under the same key breaks
// GCM catastrophically (it leaks the authentication subkey and XOR of the
// plaintexts), so a fixed nonce must never be used here.
func (s *gmCipherSuite) Encrypt(key, plaintext, aad []byte) ([]byte, error) {
sk, err := sm4KeyFrom(key)
if err != nil {
return nil, err
}
nonce, err := GenerateNonce(gcmNonceSize)
if err != nil {
return nil, err
}
gcm, err := NewSM4GCM(sk, nonce)
if err != nil {
return nil, err
}
// Seal appends to dst, so passing nonce as dst prepends it to the output.
return gcm.Seal(nonce, nonce, plaintext, aad), nil
}
func (s *internationalCipherSuite) Encrypt(key, plaintext, aad []byte) ([]byte, error) {
return EncryptAES256GCM(key, plaintext, aad)
}
// Decrypt reverses Encrypt: it splits the leading nonce off the ciphertext.
func (s *gmCipherSuite) Decrypt(key, ciphertext, aad []byte) ([]byte, error) {
sk, err := sm4KeyFrom(key)
if err != nil {
return nil, err
}
if len(ciphertext) < gcmNonceSize+gcmTagSize {
return nil, ErrDecryptionFailed
}
nonce, ct := ciphertext[:gcmNonceSize], ciphertext[gcmNonceSize:]
gcm, err := NewSM4GCM(sk, nonce)
if err != nil {
return nil, err
}
plaintext, err := gcm.Open(nil, nonce, ct, aad)
if err != nil {
return nil, ErrDecryptionFailed
}
return plaintext, nil
}
func (s *internationalCipherSuite) Decrypt(key, ciphertext, aad []byte) ([]byte, error) {
return DecryptAES256GCM(key, ciphertext, aad)
}
// Hash computes a hash using the cipher suite's hash algorithm
func (s *gmCipherSuite) Hash(data []byte) []byte {
return SM3(data)
}
func (s *internationalCipherSuite) Hash(data []byte) []byte {
return HashSHA256(data)
}
// NewHash creates a new hash instance
func (s *gmCipherSuite) NewHash() hash.Hash {
return NewSM3()
}
func (s *internationalCipherSuite) NewHash() hash.Hash {
return crypto.SHA256.New()
}
// DeriveKey derives a key of arbitrary length using HKDF-SM3 (RFC 5869).
func (s *gmCipherSuite) DeriveKey(salt, ikm []byte, info string, length int) ([]byte, error) {
return hkdfSM3(ikm, salt, []byte(info), length)
}
// hmacSM3 computes HMAC-SM3 (RFC 2104) with a 64-byte block size.
func hmacSM3(key, data []byte) []byte {
const blockSize = 64
if len(key) > blockSize {
key = SM3(key)
}
padded := make([]byte, blockSize)
copy(padded, key)
ipad := make([]byte, blockSize)
opad := make([]byte, blockSize)
for i := 0; i < blockSize; i++ {
ipad[i] = padded[i] ^ 0x36
opad[i] = padded[i] ^ 0x5c
}
inner := NewSM3()
inner.Write(ipad)
inner.Write(data)
innerSum := inner.Sum(nil)
outer := NewSM3()
outer.Write(opad)
outer.Write(innerSum)
return outer.Sum(nil)
}
// hkdfSM3 implements the full HKDF construction (extract-then-expand) on SM3.
//
// The previous implementation produced a single 32-byte block and then repeated
// it to fill longer outputs, so a 64-byte key was really only 32 bytes of
// entropy repeated twice. This version follows RFC 5869 properly.
func hkdfSM3(ikm, salt, info []byte, length int) ([]byte, error) {
const hashLen = 32
if length <= 0 {
return nil, errors.New("HKDF-SM3: invalid output length")
}
if length > 255*hashLen {
return nil, errors.New("HKDF-SM3: requested output too long")
}
// Extract: PRK = HMAC-SM3(salt, IKM)
if salt == nil {
salt = make([]byte, hashLen)
}
prk := hmacSM3(salt, ikm)
// Expand: T(n) = HMAC-SM3(PRK, T(n-1) || info || n)
out := make([]byte, 0, length)
var prev []byte
for counter := byte(1); len(out) < length; counter++ {
data := make([]byte, 0, len(prev)+len(info)+1)
data = append(data, prev...)
data = append(data, info...)
data = append(data, counter)
prev = hmacSM3(prk, data)
out = append(out, prev...)
}
return out[:length], nil
}
func (s *internationalCipherSuite) DeriveKey(salt, ikm []byte, info string, length int) ([]byte, error) {
return DeriveKey(salt, ikm, info, length)
}
// EncodePublicKey encodes a public key to bytes
func (s *gmCipherSuite) EncodePublicKey(publicKey interface{}) ([]byte, error) {
if pub, ok := publicKey.(*SM2PublicKey); ok {
return EncodeSM2PublicKey(pub)
}
return nil, ErrInvalidCurve
}
func (s *internationalCipherSuite) EncodePublicKey(publicKey interface{}) ([]byte, error) {
if pub, ok := publicKey.(*ecdsa.PublicKey); ok {
return EncodePublicKey(pub)
}
return nil, ErrInvalidCurve
}
// ParsePublicKey parses a public key from bytes
func (s *gmCipherSuite) ParsePublicKey(data []byte) (interface{}, error) {
return ParseSM2PublicKey(data)
}
func (s *internationalCipherSuite) ParsePublicKey(data []byte) (interface{}, error) {
return ParsePublicKey(data)
}
// GetCurve returns the elliptic curve for the cipher suite
func (s *gmCipherSuite) GetCurve() elliptic.Curve {
return SM2P256V1
}
func (s *internationalCipherSuite) GetCurve() elliptic.Curve {
return CurveP256
}