android-如何从以前生成的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个字节.

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

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

编码后的密钥应包含重建专用密钥所需的所有必需信息,而无需指定其他参数,就像您需要对简化的公用密钥进行操作一样.

转载注明原文:android-如何从以前生成的ECDSA两个编码密钥对构造私钥? - 代码日志