53 lines
1.4 KiB
Go
53 lines
1.4 KiB
Go
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
|
||
} |