项目场景:
之前用Java完成了对接C语言的ecdsa加密算法调试,想再完成Java与Go的对接,但遇到了问题,先简单说一下第一个问题:
1.生的秘钥长度不一样。
测试过程
Java生成秘钥的代码:
public void run() {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
ECGenParameterSpec kpgparams = new ECGenParameterSpec("secp256r1");
keyPairGenerator.initialize(kpgparams);
KeyPair keyPair = keyPairGenerator.generateKeyPair() ;
ECPublicKey ecPublicKey = (ECPublicKey)keyPair.getPublic();
System.out.println("ecPublicKey base64: " + new String(Base64.encodeBase64(ecPublicKey.getEncoded())));
ECPrivateKey ecPrivateKey = (ECPrivateKey)keyPair.getPrivate();
System.out.println("ecPrivateKey base64: " + new String(Base64.encodeBase64(ecPrivateKey.getEncoded())));
}
输出:
ecPublicKey base64: MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEZaZshlnMx2O2sccuOyk+yv5fmSUFubOm9xTeo/8ldebImyiIdj/pYWQ89nn4p3zZaOqchxBWwpmtAHj5U+LgVg==
ecPrivateKey base64: MEECAQAwEwYHKoZIzj0CAQYIKoZIzj0DAQcEJzAlAgEBBCCjMLwgVxL/Wefblay5WW79mL2/CGovqWzAAdLTGG6G5w==
秘钥长度(因为有随机值的存在,长度不固定,但相差不是太大)
- PublicKey长度:124
- PrivateKey长度:92
Go生成秘钥代码
func main{
privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err!= nil {
fmt.Println("密钥生成失败:", err)
}
if privateKey == nil {
return
}
// 编码私钥
encodedPrivateKey := base64.StdEncoding.EncodeToString(privateKey.D.Bytes())
fmt.Println("Base64 编码的私钥:", encodedPrivateKey)
// 编码公钥
encodedPublicKey := base64.StdEncoding.EncodeToString(elliptic.Marshal(privateKey.Curve, privateKey.PublicKey.X, privateKey.PublicKey.Y))
fmt.Println("Base64 编码的公钥:", encodedPublicKey)
}
输出:
privateKey: MHcCAQEEIE9ovhhMLuu/azKmJLCVJJuJ4sLOzp9cqVdNjc/U6Z2zoAoGCCqGSM49AwEHoUQDQgAE5B0dCD9fdHuoqe+/hWgvof9FLYf1jAEFF8asbe8YFp+1BKraAxNelMy5/JPfj2ThDR5uKORUiCqRlFc5TQIQSA==
publicKey: MTAzMTc4NzY4NDE0ODYwODgyMjQ3NjE4NTMxNzE1NDY2NTY3OTY2MTU3MjEwMTc3MTIzNDA4MDQ1OTkxMDQwMzMyNTM2ODAwMDg5NzU5KzgxODc2ODcyMTU2MzAxNTYyNjc1NDMzMzg5MjI3MDI5NTU4MjU1NTc4NTUxNzQ4MDk2MDQ2MDQwNjk2MDcyMzU2MzcxMjU5MDY4NDg4
秘钥长度(因为有随机值的存在,长度不固定,但相差不是太大)
- PublicKey长度:208
- PrivateKey长度:164
原因分析:
在网上搜索两种语音生成 secp256r1 秘钥的代码,都是上述代码,但是输出的秘钥长度不一样,暂不清楚原因。
解决方案:
暂未解决。