我正在尝试使用 web3j 使用生成的密钥制作 ECC。我有ECKeyPair对象,但cipher.init()
需要第二个参数是Key
对象。ECKeyPair返回BigInteger
私钥和公钥,我如何将它们转换为KeyPair
哪个持有PrivateKey
和PublicKey
对象?
我试过(参考:CryptoUtil.java):
private fun decodeKeyPair(ecKeyPair: ECKeyPair): KeyPair {
val xp = getNamedCurveByName("secp256k1")
val p = ECNamedCurveSpec("secp256k1", xp.curve, xp.g, xp.n, xp.h, null)
val curve = convertCurve(p.curve)
val g = EC5Util.convertPoint(curve, p.generator, false)
val n = p.order
val h = BigInteger.valueOf(p.cofactor.toLong())
val dp = ECDomainParameters(curve, g, n, h)
val bytes = Numeric.toBytesPadded(ecKeyPair.publicKey, 64)
val x = Numeric.toBigInt(Arrays.copyOfRange(bytes, 0, 32))
val y = Numeric.toBigInt(Arrays.copyOfRange(bytes, 32, 64))
val q = curve.createPoint(x, y)
val publicKey = BCECPublicKey(
"EC",
ECPublicKeyParameters(q, dp),
BouncyCastleProvider.CONFIGURATION
)
val privateKey = BCECPrivateKey(
"EC",
ECPrivateKeyParameters(ecKeyPair.privateKey, dp),
publicKey,
p,
BouncyCastleProvider.CONFIGURATION
)
return KeyPair(publicKey, privateKey)
}
但这会返回一个错误:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'org.bouncycastle.math.ec.ECCurve org.bouncycastle.jce.spec.ECParameterSpec.getCurve()' on a null object reference
有没有其他方法可以将 Web3j ECKeyPair转换为KeyPair
?