在android中,我使用以下代码生成KeyPair
fun generateKeyPair(): KeyPair {
val keyGen = KeyPairGenerator.getInstance("ECDH", BouncyCastleProvider())
val ecSpec = ECGenParameterSpec("prime256v1")
val random = SecureRandom.getInstance("SHA1PRNG")
keyGen.initialize(ecSpec,random)
return keyGen.generateKeyPair()
}
它返回KeyPair,在转换为十六进制后我得到
public:3059301306072A8648CE3D020106082A8648CE3D03010703420004CF2245EC08585CBDE04CB10AA4D33A4C5AED224D28AA6A6AB840DE694C0DE1F73064922D6759D424B04E34DDA0885FE2C80FE80DC44F4BB5579E515519B66583
private:308193020100301306072A8648CE3D020106082A8648CE3D030107047930770201010420A7BAA38400D1AF60B203C49B378296FF3A7D1989A05A7BE55C0C9E04516CF183A00A06082A8648CE3D030107A14403420004CF2245EC08585CBDE04CB10AA4D33A4C5AED224D28AA6A6AB840DE694C0DE1F73064922D6759D424B04E34DDA0885FE2C80FE80DC44F4BB5579E515519B66583
@Throws(NoSuchAlgorithmException::class, InvalidKeySpecException::class)
fun getPublicKey(pk: ByteArray?): PublicKey {
val publicKeySpec: EncodedKeySpec = X509EncodedKeySpec(pk)
val kf = KeyFactory.getInstance(KeyProperties.KEY_ALGORITHM_EC)
return kf.generatePublic(publicKeySpec)
}
fun hexStringToByteArray(hexString: String): ByteArray? {
val bytes = ByteArray(hexString.length / 2)
var i = 0
while (i < hexString.length) {
val sub = hexString.substring(i, i + 2)
val intVal = sub.toInt(16)
bytes[i / 2] = intVal.toByte()
val hex = String.format("0x%x", bytes[i / 2])
i += 2
}
return bytes
}
fun bytesToHex(bytes: ByteArray): String {
val HEX_ARRAY = "0123456789ABCDEF".toCharArray()
val hexChars = CharArray(bytes.size * 2)
for (j in bytes.indices) {
val v = bytes[j].toInt() and 0xFF // Here is the conversion
hexChars[j * 2] = HEX_ARRAY[v.ushr(4)]
hexChars[j * 2 + 1] = HEX_ARRAY[v and 0x0F]
}
return String(hexChars)
}
我也可以生成共享秘密
val keyAgreement = KeyAgreement.getInstance("ECDH", BouncyCastleProvider())
keyAgreement.init(private)
keyAgreement.doPhase(getPublicKey(hexStringToByteArray("3059301306072A8648CE3D020106082A8648CE3D030107034200046E69A6A17934F61F7A601262F66A0414BE8BCF9D7DE423A929A5A0EF6D4C0D1597C3CFBE6C16E8236F245FAE0D7793A225D6E1CD3C0E3830C4E11C8E120848E2")), true)
val sharedSecret = keyAgreement.generateSecret()
val secretHex = bytesToHex(sharedSecret)
共享密钥 5AA6C5095C8D89C6A9C16C71047E38090EDB90CE3A94B70359B325992B2DCC68
现在使用相同的 prime256v1 进入 iOS 我正在获取以下数据
private:62f24e3927aa953ae0d6f851b403481387aecd4ceb192eb1065a5897a9971d6d public:b4a7002c6bfb9f1d0fc6fb6a85681c8c2f44a36ad671f5033a1fcb9e49e8709d00c53e45bcf0c46aa948deea1a0f3103c1924713e9e9fd4a9a365d23b395ddc0
现在这里有一个实际上我不明白的区别,并且在使用从 iOS 生成的公钥在 android 中生成共享密钥时,我在使用从 android 生成的公钥的 iOS 上遇到错误和错误