crypto

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: May 24, 2026 License: Apache-2.0 Imports: 32 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// GM/T 0125.1-2022 algorithm identifiers
	SGD_SM3_SM2  = "SGD_SM3_SM2"  // SM2+SM3 digital signature
	SGD_SM3_SM9  = "SGD_SM3_SM9"  // SM9+SM3 digital signature (identity-based)
	SGD_SM3_HMAC = "SGD_SM3_HMAC" // SM3 keyed-HMAC
	SGD_SM2_3    = "SGD_SM2_3"    // SM2 public key encryption (JWE key wrapping)
	SGD_SM9_3    = "SGD_SM9_3"    // SM9 encryption (JWE key wrapping)
	SGD_SM4_CCM  = "SGD_SM4_CCM"  // SM4 in CCM mode (JWE content encryption)
	SGD_SM4_GCM  = "SGD_SM4_GCM"  // SM4 in GCM mode (JWE content encryption)
)
View Source
const (
	// SM4GCMTagSize is the GCM authentication tag size for SM4 (128 bits).
	SM4GCMTagSize = 16
	// SM4CCMTagSize is the CCM authentication tag size for SM4 (128 bits).
	SM4CCMTagSize = 16
)
View Source
const (
	SM4BlockSize    = sm4.BlockSize
	SM4GCMNonceSize = 12
	SM4CCMNonceSize = 12
)
View Source
const (
	// SM9HIDSign is the system-defined hid value for SM9 digital signature per GB/T 41389-2022.
	SM9HIDSign byte = 0x01
	// SM9HIDEncrypt is the system-defined hid value for SM9 encryption per GB/T 41389-2022.
	SM9HIDEncrypt byte = 0x03
)

Variables

View Source
var (
	ErrInvalidJWECompact = errors.New("kexcore/crypto: invalid JWE compact serialization")
	ErrInvalidJWEParts   = errors.New("kexcore/crypto: JWE compact serialization must have exactly 5 parts")
	ErrJWEKeyDecrypt     = errors.New("kexcore/crypto: failed to decrypt JWE encrypted key")
	ErrJWEContentDecrypt = errors.New("kexcore/crypto: failed to decrypt JWE content")
	ErrJWEHeaderMismatch = errors.New("kexcore/crypto: JWE header algorithm mismatch")
	ErrJWEUnsupportedEnc = errors.New("kexcore/crypto: unsupported JWE content encryption algorithm")
)
View Source
var (
	ErrPEMDecode             = errors.New("PEM decode failed")
	ErrUnsupportedFormat     = errors.New("key is neither in PKCS#1 nor PKCS#8 format")
	ErrUnsupportedPrivateKey = errors.New("unsupported key type, must be RSA, ECDSA, ED25519 or SM2 private key")
)
View Source
var (
	ErrInvalidSM2PrivateKey = errors.New("kexcore/crypto: sm2 invalid private key")
	ErrInvalidSM2PublicKey  = errors.New("kexcore/crypto: sm2 invalid public key")
)
View Source
var (
	ErrInvalidSM4KeySize    = errors.New("kexcore/crypto: sm4 invalid key size, must be 16 bytes")
	ErrInvalidSM4IVSize     = errors.New("kexcore/crypto: sm4 invalid IV size, must be 16 bytes")
	ErrInvalidSM4NonceSize  = errors.New("kexcore/crypto: sm4 invalid nonce size for GCM, must be 12 bytes")
	ErrInvalidCiphertextLen = errors.New("kexcore/crypto: sm4 ciphertext is not a multiple of the block size")
)
View Source
var (
	ErrInvalidSM9EncryptMasterPublicKey = errors.New("kexcore/crypto: sm9 invalid encrypt master public key")
	ErrInvalidSM9EncryptPrivateKey      = errors.New("kexcore/crypto: sm9 invalid encrypt private key")
	ErrInvalidSM9SignMasterPrivateKey   = errors.New("kexcore/crypto: sm9 invalid sign master private key")
	ErrInvalidSM9SignMasterPublicKey    = errors.New("kexcore/crypto: sm9 invalid sign master public key")
)
View Source
var ErrCipherTextBlockSize = errors.New("ciphertext block size is too short")
View Source
var ErrUnsupportedAlgorithm = errors.New("unsupported signing algorithm")

Functions

func BuildSM2SigningInput deprecated

func BuildSM2SigningInput(protectedHeaders any, payload []byte) ([]byte, error)

BuildSM2SigningInput reconstructs the JWS signing input from the protected header and payload of a JWS message. Returns base64url(header) + "." + base64url(payload). protectedHeaders can be any value that json.Marshal can handle (e.g. jws.Headers).

Deprecated: Use BuildSigningInput instead. This function is kept for backward compatibility.

func BuildSigningInput

func BuildSigningInput(protectedHeaders any, payload []byte) ([]byte, error)

BuildSigningInput reconstructs the JWS signing input from the protected header and payload of a JWS message. Returns base64url(header) + "." + base64url(payload). protectedHeaders can be any value that json.Marshal can handle (e.g. jws.Headers).

func BytesToPrivateKey

func BytesToPrivateKey(b []byte) (crypto.PublicKey, string, error)

func DecryptAES

func DecryptAES(data string, key string) (string, error)

func DecryptBytesAES

func DecryptBytesAES(cipherText []byte, key string) ([]byte, error)

func DecryptBytesSM4

func DecryptBytesSM4(cipherText []byte, key string) ([]byte, error)

func DecryptSM4

func DecryptSM4(data string, key string) (string, error)

func EncryptAES

func EncryptAES(data string, key string) (string, error)

func EncryptBytesAES

func EncryptBytesAES(plainText []byte, key string) ([]byte, error)

func EncryptBytesSM4

func EncryptBytesSM4(plainText []byte, key string) ([]byte, error)

func EncryptSM4

func EncryptSM4(data string, key string) (string, error)

func GetHashAlgorithm

func GetHashAlgorithm(sigAlgorithm string) (hash.Hash, error)

func HashString

func HashString(hash hash.Hash, s string, firstHalf bool) string

func IsSM2Algorithm

func IsSM2Algorithm(alg string) bool

IsSM2Algorithm returns true if the given algorithm identifier is an SM2 signing algorithm (SGD_SM3_SM2 or SM2-SM3 alias).

func IsSM9Algorithm

func IsSM9Algorithm(alg string) bool

IsSM9Algorithm returns true if the given algorithm identifier is an SM9 signing algorithm (SGD_SM3_SM9).

func ParseSM9SignMasterPublicKey

func ParseSM9SignMasterPublicKey(xBase64 string) (*sm9.SignMasterPublicKey, error)

ParseSM9SignMasterPublicKey parses an SM9 signing master public key from a JWK x field.

func SM2CalculateZA

func SM2CalculateZA(publicKey *ecdsa.PublicKey, uid []byte) ([]byte, error)

func SM2Decrypt

func SM2Decrypt(privateKey *sm2.PrivateKey, ciphertext []byte) ([]byte, error)

func SM2DecryptJWE

func SM2DecryptJWE(privateKey *sm2.PrivateKey, compact string) ([]byte, error)

SM2DecryptJWE decrypts a GM/T 0125.3 JWE compact serialization with SM2 key wrapping (SGD_SM2_3) and SM4-GCM content encryption (SGD_SM4_GCM).

Decryption flow:

  1. Parse the JWE compact serialization into its 5 components.
  2. Verify the JWE protected header uses SGD_SM2_3 + SGD_SM4_GCM.
  3. Decrypt the encrypted key using the SM2 private key to recover the CEK.
  4. Decrypt the ciphertext using SM4-GCM with the recovered CEK, using the base64url-encoded protected header as AAD.

func SM2Encrypt

func SM2Encrypt(publicKey *ecdsa.PublicKey, plaintext []byte) ([]byte, error)

func SM2EncryptASN1

func SM2EncryptASN1(publicKey *ecdsa.PublicKey, plaintext []byte) ([]byte, error)

func SM2EncryptJWE

func SM2EncryptJWE(publicKey *ecdsa.PublicKey, plaintext []byte) (string, error)

SM2EncryptJWE encrypts plaintext using the GM/T 0125.3 JWE specification with SM2 key wrapping (SGD_SM2_3) and SM4-GCM content encryption (SGD_SM4_GCM).

Encryption flow:

  1. Generate a random 128-bit Content Encryption Key (CEK).
  2. Wrap the CEK using SM2 public key encryption (SGD_SM2_3, ASN.1 encoding).
  3. Generate a random 96-bit IV for SM4-GCM.
  4. Encrypt plaintext using SM4-GCM with the CEK, using the base64url-encoded protected header as additional authenticated data (AAD).

Returns the JWE compact serialization:

base64url(protected_header) . base64url(encrypted_key) . base64url(iv) . base64url(ciphertext) . base64url(tag)

func SM2GenerateKey

func SM2GenerateKey() (*sm2.PrivateKey, error)

func SM2KeyExchange

func SM2KeyExchange(priv *sm2.PrivateKey, peerPub *ecdsa.PublicKey, uid, peerUID []byte, keyLen int, isResponder bool) (*sm2.KeyExchange, error)

func SM2NewPrivateKey

func SM2NewPrivateKey(key []byte) (*sm2.PrivateKey, error)

func SM2NewPublicKey

func SM2NewPublicKey(key []byte) (*ecdsa.PublicKey, error)

func SM2PrivateKeyToBytes

func SM2PrivateKeyToBytes(privateKey *sm2.PrivateKey) ([]byte, error)

func SM2PrivateKeyToHex

func SM2PrivateKeyToHex(privateKey *sm2.PrivateKey) (string, error)

func SM2PublicKeyFromJWK

func SM2PublicKeyFromJWK(crv, xBase64, yBase64 string) (*ecdsa.PublicKey, error)

SM2PublicKeyFromJWK parses an SM2 public key from JWK fields.

func SM2PublicKeyToBytes

func SM2PublicKeyToBytes(publicKey *ecdsa.PublicKey) ([]byte, error)

func SM2PublicKeyToHex

func SM2PublicKeyToHex(publicKey *ecdsa.PublicKey) (string, error)

func SM2Sign

func SM2Sign(privateKey *sm2.PrivateKey, data []byte) ([]byte, error)

func SM2SignWithUID

func SM2SignWithUID(privateKey *sm2.PrivateKey, uid, data []byte) ([]byte, error)

func SM2Verify

func SM2Verify(publicKey *ecdsa.PublicKey, data, signature []byte) bool

func SM2VerifyWithUID

func SM2VerifyWithUID(publicKey *ecdsa.PublicKey, uid, data, signature []byte) bool

func SM3HMAC

func SM3HMAC(key, data []byte) []byte

SM3HMAC returns the SM3-based HMAC of data using the given key (SGD_SM3_HMAC).

func SM3HMACHex

func SM3HMACHex(key, data []byte) string

SM3HMACHex returns the SM3-based HMAC of data as a hex-encoded string.

func SM3HMACVerify

func SM3HMACVerify(key, data, mac []byte) bool

SM3HMACVerify checks whether the given HMAC matches the SM3-HMAC of data.

func SM3Hash

func SM3Hash(data []byte) []byte

func SM3HashHex

func SM3HashHex(data []byte) string

func SM3HashString

func SM3HashString(data string) []byte

func SM3HashStringHex

func SM3HashStringHex(data string) string

func SM3Sum

func SM3Sum(data []byte) [sm3.Size]byte

func SM4DecryptCBC

func SM4DecryptCBC(key, ciphertext []byte) ([]byte, error)

SM4DecryptCBC decrypts ciphertext using SM4 in CBC mode. Expects: IV || ciphertext format.

func SM4DecryptCBCWithIV

func SM4DecryptCBCWithIV(key, iv, ciphertext []byte) ([]byte, error)

SM4DecryptCBCWithIV decrypts ciphertext using SM4 in CBC mode with provided IV.

func SM4DecryptCCM

func SM4DecryptCCM(key, ciphertext, additionalData []byte) ([]byte, error)

SM4DecryptCCM decrypts ciphertext using SM4 in CCM mode. Expects: nonce || ciphertext format.

func SM4DecryptCCMWithNonce

func SM4DecryptCCMWithNonce(key, nonce, ciphertext, additionalData []byte) ([]byte, error)

SM4DecryptCCMWithNonce decrypts ciphertext using SM4 in CCM mode with provided nonce.

func SM4DecryptECB

func SM4DecryptECB(key, ciphertext []byte) ([]byte, error)

SM4DecryptECB decrypts ciphertext using SM4 in ECB mode. WARNING: ECB mode is NOT secure. See SM4EncryptECB for details.

func SM4DecryptGCM

func SM4DecryptGCM(key, ciphertext, additionalData []byte) ([]byte, error)

SM4DecryptGCM decrypts ciphertext using SM4 in GCM mode. Expects: nonce || ciphertext format.

func SM4DecryptGCMWithNonce

func SM4DecryptGCMWithNonce(key, nonce, ciphertext, additionalData []byte) ([]byte, error)

SM4DecryptGCMWithNonce decrypts ciphertext using SM4 in GCM mode with provided nonce.

func SM4EncryptCBC

func SM4EncryptCBC(key, plaintext []byte) ([]byte, error)

SM4EncryptCBC encrypts plaintext using SM4 in CBC mode. The IV is randomly generated and prepended to the ciphertext. Returns: IV || ciphertext

func SM4EncryptCBCWithIV

func SM4EncryptCBCWithIV(key, iv, plaintext []byte) ([]byte, error)

SM4EncryptCBCWithIV encrypts plaintext using SM4 in CBC mode with provided IV. Use SM4EncryptCBC for automatic IV generation.

func SM4EncryptCCM

func SM4EncryptCCM(key, plaintext, additionalData []byte) ([]byte, error)

SM4EncryptCCM encrypts plaintext using SM4 in CCM mode. The nonce is randomly generated and prepended to the ciphertext. Returns: nonce || ciphertext (with auth tag)

func SM4EncryptCCMWithNonce

func SM4EncryptCCMWithNonce(key, nonce, plaintext, additionalData []byte) ([]byte, error)

SM4EncryptCCMWithNonce encrypts plaintext using SM4 in CCM mode with provided nonce. WARNING: Never reuse a nonce with the same key. Use SM4EncryptCCM for automatic nonce generation.

func SM4EncryptECB

func SM4EncryptECB(key, plaintext []byte) ([]byte, error)

SM4EncryptECB encrypts plaintext using SM4 in ECB mode. WARNING: ECB mode is NOT secure for most use cases. It does not provide semantic security and leaks data patterns. Use CBC or GCM mode instead. This function is provided for compatibility with legacy systems only.

func SM4EncryptGCM

func SM4EncryptGCM(key, plaintext, additionalData []byte) ([]byte, error)

SM4EncryptGCM encrypts plaintext using SM4 in GCM mode. The nonce is randomly generated and prepended to the ciphertext. Returns: nonce || ciphertext (with auth tag)

func SM4EncryptGCMWithNonce

func SM4EncryptGCMWithNonce(key, nonce, plaintext, additionalData []byte) ([]byte, error)

SM4EncryptGCMWithNonce encrypts plaintext using SM4 in GCM mode with provided nonce. WARNING: Never reuse a nonce with the same key. Use SM4EncryptGCM for automatic nonce generation.

func SM4GenerateKey

func SM4GenerateKey() ([]byte, error)

func SM4KeyFromHex

func SM4KeyFromHex(hexKey string) ([]byte, error)

func SM4KeyToHex

func SM4KeyToHex(key []byte) string

func SM4NewCipher

func SM4NewCipher(key []byte) (cipher.Block, error)

func SM9Decrypt

func SM9Decrypt(userKey *sm9.EncryptPrivateKey, uid []byte, ciphertext []byte) ([]byte, error)

SM9Decrypt decrypts SM9-encrypted ciphertext using the user's encryption private key.

func SM9DecryptJWE

func SM9DecryptJWE(userKey *sm9.EncryptPrivateKey, uid []byte, compact string) ([]byte, error)

SM9DecryptJWE decrypts a GM/T 0125.3 JWE compact serialization with SM9 key wrapping (SGD_SM9_3) and SM4 content encryption.

func SM9Encrypt

func SM9Encrypt(masterPubKey *sm9.EncryptMasterPublicKey, uid []byte, plaintext []byte) ([]byte, error)

SM9Encrypt encrypts plaintext using SM9 public key encryption.

func SM9EncryptJWE

func SM9EncryptJWE(masterPubKey *sm9.EncryptMasterPublicKey, uid []byte, enc string, plaintext []byte) (string, error)

SM9EncryptJWE encrypts plaintext using the GM/T 0125.3 JWE specification with SM9 key wrapping (SGD_SM9_3) and SM4 content encryption.

The enc parameter specifies the content encryption algorithm:

  • SGD_SM4_GCM: SM4 in GCM mode (default)
  • SGD_SM4_CCM: SM4 in CCM mode

func SM9GenerateEncryptMasterKey

func SM9GenerateEncryptMasterKey() (*sm9.EncryptMasterPrivateKey, error)

SM9GenerateEncryptMasterKey generates an SM9 encryption master key pair.

func SM9GenerateEncryptUserKey

func SM9GenerateEncryptUserKey(masterKey *sm9.EncryptMasterPrivateKey, uid []byte) (*sm9.EncryptPrivateKey, error)

SM9GenerateEncryptUserKey generates an SM9 encryption user private key from the master key.

func SM9GenerateSignMasterKey

func SM9GenerateSignMasterKey() (*sm9.SignMasterPrivateKey, error)

SM9GenerateSignMasterKey generates an SM9 signature master key pair.

func SM9GenerateSignUserKey

func SM9GenerateSignUserKey(masterKey *sm9.SignMasterPrivateKey, uid []byte) (*sm9.SignPrivateKey, error)

SM9GenerateSignUserKey generates an SM9 signature user private key from the master key.

func SM9Sign

func SM9Sign(userKey *sm9.SignPrivateKey, hash []byte) ([]byte, error)

SM9Sign signs data using the SM9 signature user private key.

func SM9UnwrapKey

func SM9UnwrapKey(userKey *sm9.EncryptPrivateKey, uid []byte, cipherDER []byte, kLen int) ([]byte, error)

SM9UnwrapKey unwraps an SM9-encrypted key using the user's encryption private key.

func SM9Verify

func SM9Verify(masterPubKey *sm9.SignMasterPublicKey, uid []byte, hash, signature []byte) bool

SM9Verify verifies an SM9 signature using the master public key and user identifier.

func SM9WrapKey

func SM9WrapKey(masterPubKey *sm9.EncryptMasterPublicKey, uid []byte, kLen int) ([]byte, []byte, error)

SM9WrapKey wraps a key of kLen bytes using SM9 encryption (SGD_SM9_3). Returns the wrapped key and the ASN.1-encoded encryption metadata.

func Sign

func Sign(payload interface{}, signer *Signer) (string, error)

Sign marshals payload to JSON and signs it.

func SignPayload

func SignPayload(payload []byte, signer *Signer) (string, error)

SignPayload signs raw payload bytes.

func VerifySM2JWSSignature

func VerifySM2JWSSignature(signingInput []byte, signature []byte, pubKey *ecdsa.PublicKey) error

VerifySM2JWSSignature verifies an SM2 JWS signature using SM3 hash. This function handles the full verification flow: decode the signature, reconstruct the signing input, hash with SM3, and verify with SM2.

Parameters:

  • signingInput: the JWS signing input (base64url(header) + "." + base64url(payload))
  • signature: the raw signature bytes from the JWS
  • pubKey: the SM2 public key for verification

func VerifySM9JWSSignature

func VerifySM9JWSSignature(signingInput []byte, signature []byte, masterPubKey *sm9.SignMasterPublicKey, uid []byte) error

VerifySM9JWSSignature verifies an SM9 JWS signature using SM3 hash. SM9 verification requires the master public key and the user identifier (uid). The uid must be extracted from the JWS protected header (custom "uid" parameter).

Parameters:

  • signingInput: the JWS signing input (base64url(header) + "." + base64url(payload))
  • signature: the raw signature bytes from the JWS
  • masterPubKey: the SM9 signing master public key
  • uid: the user identifier used to derive the signing key

Types

type JWKSKey

type JWKSKey struct {
	Kid string
	Alg string
	Use string
	Key any
}

JWKSKey represents a parsed key from a JWKS endpoint. The Key field is one of: *ecdsa.PublicKey (SM2), *sm9.SignMasterPublicKey (SM9). Standard keys (RSA, ECDSA, EdDSA) are NOT handled here — use jwx for those.

func FindJWKSKey

func FindJWKSKey(keys []JWKSKey, kid, alg string) *JWKSKey

FindJWKSKey finds a key by kid and algorithm from a parsed JWKS key list.

func ParseJWKSBytes

func ParseJWKSBytes(data []byte) ([]JWKSKey, error)

ParseJWKSBytes parses JWKS JSON and returns keys with GM/T algorithms (SGD_SM3_SM2, SGD_SM3_SM9). Standard algorithm keys are skipped — use jwx for those.

type SM2JWK

type SM2JWK struct {
	Kty string `json:"kty"`
	Crv string `json:"crv"`
	X   string `json:"x"`
	Y   string `json:"y"`
	Alg string `json:"alg,omitempty"`
	Kid string `json:"kid,omitempty"`
	Use string `json:"use,omitempty"`
}

SM2JWK represents a JSON Web Key for an SM2 public key per GM/T 0125.4-2022. SM2 keys use kty "EC" with crv "SM2-P-256" and standard x/y coordinates. This type exists because the jwx library does not recognize the SM2 curve or the SGD_SM3_SM2 algorithm, so we cannot use jwk.Import or jwk.ParseKey.

func NewSM2JWK

func NewSM2JWK(pubKey *ecdsa.PublicKey, kid, use string) SM2JWK

NewSM2JWK constructs an SM2JWK from an SM2 public key. Coordinates are encoded as base64url per RFC 7518 §6.2.1.2.

type SM3

type SM3 struct {
	// contains filtered or unexported fields
}

func NewSM3

func NewSM3() *SM3

func (*SM3) BlockSize

func (s *SM3) BlockSize() int

func (*SM3) Reset

func (s *SM3) Reset()

func (*SM3) Size

func (s *SM3) Size() int

func (*SM3) Sum

func (s *SM3) Sum(b []byte) []byte

func (*SM3) Write

func (s *SM3) Write(data []byte) (int, error)

type SM9SignJWK

type SM9SignJWK struct {
	Kty string `json:"kty"`
	Crv string `json:"crv"`
	X   string `json:"x"`
	Alg string `json:"alg,omitempty"`
	Kid string `json:"kid,omitempty"`
	Use string `json:"use,omitempty"`
}

SM9SignJWK represents a JSON Web Key for an SM9 signing master public key. SM9 uses identity-based cryptography (IBC) where the master public key is used for verification and user signing keys are derived from the master key + uid. The x field contains the ASN.1 DER-encoded master public key.

func NewSM9SignJWK

func NewSM9SignJWK(masterPubKey *sm9.SignMasterPublicKey, kid, use string) (SM9SignJWK, error)

NewSM9SignJWK constructs an SM9SignJWK from an SM9 signing master public key.

type Signer

type Signer struct {
	// contains filtered or unexported fields
}

Signer encapsulates key material and algorithm for JWS signing operations.

func NewSigner

func NewSigner(algorithm string, key interface{}, keyID string) (*Signer, error)

NewSigner creates a Signer for the given algorithm and key. The algorithm must be a valid JWA signature algorithm string (e.g. "RS256", "ES384", "EdDSA", "SGD_SM3_SM2").

func (*Signer) Algorithm

func (s *Signer) Algorithm() string

Algorithm returns the JWA signature algorithm string.

func (*Signer) Sign

func (s *Signer) Sign(payload []byte) (string, error)

Sign signs the payload and returns the compact serialized JWS.

Jump to

Keyboard shortcuts

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