gmsm
gmsm copied to clipboard
sm2中的P256Sm2方法返回值是elliptic.Curve,但该接口大部分方法已经是Deprecated状态
当前go版本是1.23.4。
func HexToSM2PrivateKey(hexKey string) (*sm2.PrivateKey, error) {
// 将 16 进制字符串转换为字节数组
privateKeyBytes, err := hex.DecodeString(hexKey)
if err != nil {
return nil, fmt.Errorf("failed to decode hex: %w", err)
}
curve := sm2.P256Sm2()
curve.Params()
D := new(big.Int).SetBytes(privateKeyBytes)
// 根据 D 生成公钥点 (x, y)
x, y := curve.ScalarBaseMult(privateKeyBytes)
// 生成 sm2 私钥结构
privateKey := &sm2.PrivateKey{
PublicKey: sm2.PublicKey{
Curve: curve,
X: x,
Y: y,
},
D: D,
}
return privateKey, nil
}