生成了这样的私钥:
fun getKeyPair(): Pair<ByteArray, ByteArray> {
Security.addProvider(provider)
val generator = KeyPairGenerator.getInstance("ECDSA")
val ecSpec = ECNamedCurveTable.getParameterSpec("secp256r1")
generator.initialize(ecSpec)
val keyPair = generator.generateKeyPair()
val publicKey = keyPair.public as ECPublicKey
val privateKey = keyPair.private
return Pair(publicKey.q.getEncoded(true), privateKey.getEncoded())
}
公钥可以像这样重新构建:
Security.addProvider(...spongy castle provider)
val ecSpecs = ECNamedCurveTable.getParameterSpec("secp256r1")
val q = ecSpecs.curve.decodePoint(publicKeyEncoded)
val pubSpec = ECPublicKeySpec(q, ecSpecs)
val keyFactory = KeyFactory.getInstance("ECDSA")
val generatedPublic = keyFactory.generatePublic(pubSpec)
如何能够同时从字节重建私钥?
更新:
这段代码在实际的应用程序中运行良好,但在JUnit测试中不起作用:
val keyFactory = KeyFactory.getInstance("ECDSA")
val privSpec = PKCS8EncodedKeySpec(privateEncoded)
val generatedPrivate = keyFactory.generatePrivate(privSpec)
在junit测试中,我得到这个错误:
java.security.spec.InvalidKeySpecException: encoded key spec not recognised
我的私钥编码字节有150字节大小。