return
}
③测试用例
func TestSM2_Local_GenerateKeyPair(t *testing.T) {
// 生成密钥对
publicKeyObj, privateKeyObj := generateLoc()
// 输出公钥和私钥字符串
t.Log(“公钥字符串:”, PublicKeyToString(publicKeyObj))
// 040a5cccc33685eade33b0a1a40f1eea0f86ae93bd3cbb9f88fa466ca49a87bdbcd1ab65c9cb9f587a3b1f6d143f964acab78a23c2c37b1c16e2d16b796861f7bf
t.Log(“私钥字符串:”, PrivateKeyToString(privateKeyObj))
// 5b8037839b43ee13804e4c9fb3626b8949f0f58729547f0da4e8415481243b03
}
打印结果:
=== RUN TestSM2_Local_GenerateKeyPair
sm2_test.go:14: 公钥字符串:040a5cccc33685eade33b0a1a40f1eea0f86ae93bd3cbb9f88fa466ca49a87bdbcd1ab65c9cb9f587a3b1f6d143f964acab78a23c2c37b1c16e2d16b796861f7bf
sm2_test.go:16: 私钥字符串:5b8037839b43ee13804e4c9fb3626b8949f0f58729547f0da4e8415481243b03
— PASS: TestSM2_Local_GenerateKeyPair (0.00s)
PASS
2.使用公钥加密
①需求描述
要使用上面生成并缓存在redis
中的公钥字符串,对内容进行加密.
②编写代码
将公钥字符串反序列化转为公钥对象:
// StringToPublicKey 公钥字符串还原为 sm2.PublicKey 对象(与java中org.bouncycastle.crypto生成的公私钥完全互通使用)
func StringToPublicKey(publicKeyStr string) (*sm2.PublicKey, error) {
publicKeyBytes, err := hex.DecodeString(publicKeyStr)
if err != nil {
return nil, err
}
// 提取 x 和 y 坐标字节切片
curve := sm2.P256Sm2().Params()
byteLen := (curve.BitSize + 7) / 8
xBytes := publicKeyBytes[1 : byteLen+1]
yBytes := publicKeyBytes[byteLen+1 : 2*byteLen+1]
// 将字节切片转换为大整数
x := new(big.Int).SetBytes(xBytes)
y := new(big.Int).SetBytes(yBytes)
// 创建 sm2.PublicKey 对象
publicKey := &sm2.PublicKey{
C