如何从先前生成的ECDSA两种编码密钥对构造私钥?

时间:2018-12-13 15:12:40

标签: android kotlin cryptography bouncycastle ecdsa

已经生成了如下私钥:

    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个字节。

1 个答案:

答案 0 :(得分:3)

由于密钥是使用标准Key.getEncoded()编码的,因此以下标准解决方案应该可以工作:

val keyFactory = KeyFactory.getInstance("EC")
val privSpec = PKCS8EncodedKeySpec(privateEncoded)
val generatedPrivate = keyFactory.generatePrivate(privSpec)

编码后的密钥应包含重建私有密钥所需的所有必需信息,而无需指定其他参数,就像您需要为简化的公共密钥所做的那样。