
secp256r1 椭圆曲线 ecdh 中坐标无效的解决方法
在使用 secp256r1 椭圆曲线进行 ecdh 密钥协商时,如果遇到坐标无效的问题,可以通过以下方法解决:
问题描述:使用了如下代码生成密钥对和计算 ecdh 密钥,但有时会报坐标无效的错误:
keypair keypair = gettempkey(); privatekey myprivatekey = getprivatekeyfroms(myprihex); publickey othpublickey = getpublickeyfromxy(mypubhex); // ... ecdh 协商代码 ...
解决方法:确保在 getpublickeyfromxy(string hexstr) 方法中生成点时,正确地将十六进制字符串转换为 biginteger。
public static PublicKey getPublicKeyFromXY(String hexStr) {
// 从十六进制字符串中获取 x 和 y 坐标
byte[] xBytes = HexUtil.decodeHex(hexStr.substring(2, 66));
byte[] yBytes = HexUtil.decodeHex(hexStr.substring(66));
// 将 x 和 y 坐标转换为 BigInteger,并确保是正数
BigInteger x = new BigInteger(1, xBytes);
BigInteger y = new BigInteger(1, yBytes);
// 创建椭圆曲线点
ECPoint point = new ECPoint(x, y);
// 获取椭圆曲线参数规格
ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("secp256r1");
// 创建公钥
return KeyFactory.getInstance("EC", "BC").generatePublic(new ECPublicKeySpec(point, spec));
}通过确保将十六进制字符串正确转换为正数 biginteger,可以修复坐标无效的问题,从而成功计算 ecdh 密钥。










