xy-shanghai-20260721-171915/xy-shanghai/crypto.go

53 lines
1.4 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package xyshanghai
import (
"crypto/rand"
"fmt"
"github.com/tjfoc/gmsm/sm3"
"github.com/tjfoc/gmsm/sm4"
)
// SM4Encrypt 使用 SM4 算法加密数据ECB 模式PKCS7 填充)。
// key 长度必须为 16 字节。
func SM4Encrypt(key, plaintext []byte) ([]byte, error) {
if len(key) != 16 {
return nil, fmt.Errorf("sm4 key must be 16 bytes, got %d", len(key))
}
ciphertext, err := sm4.Sm4Ecb(key, plaintext, true) // true 表示加密
if err != nil {
return nil, fmt.Errorf("sm4 ecb encrypt: %w", err)
}
return ciphertext, nil
}
// SM4Decrypt 使用 SM4 算法解密数据ECB 模式PKCS7 填充)。
func SM4Decrypt(key, ciphertext []byte) ([]byte, error) {
if len(key) != 16 {
return nil, fmt.Errorf("sm4 key must be 16 bytes, got %d", len(key))
}
plaintext, err := sm4.Sm4Ecb(key, ciphertext, false) // false 表示解密
if err != nil {
return nil, fmt.Errorf("sm4 ecb decrypt: %w", err)
}
return plaintext, nil
}
// SM3WithSalt 使用 SM3 算法加盐计算哈希。
// salt 为盐值data 为待签名字符串。
func SM3WithSalt(salt []byte, data string) string {
h := sm3.New()
h.Write(salt)
h.Write([]byte(data))
return fmt.Sprintf("%x", h.Sum(nil))
}
// GenerateSM4Key 生成一个随机的 16 字节 SM4 密钥。
func GenerateSM4Key() ([]byte, error) {
key := make([]byte, 16)
_, err := rand.Read(key)
if err != nil {
return nil, fmt.Errorf("generate random key: %w", err)
}
return key, nil
}