首页 > 解决方案 > 在 Java 中导入 ANSI X9.63 格式的密钥对

问题描述

我在 iOS 上生成了一个密钥对,并使用以下代码创建了一个数据表示:

var publicKey, privateKey: SecKey?
let keyattribute = [
    kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom,
    kSecAttrKeySizeInBits as String : 256
    ] as CFDictionary
SecKeyGeneratePair(keyattribute, &publicKey, &privateKey)

var error: Unmanaged<CFError>?
let pubkeyRep = SecKeyCopyExternalRepresentation(publicKey!, &error) as Data?
let prikeyRep = SecKeyCopyExternalRepresentation(privateKey!, &error) as Data?

根据 Apple 的文档,SecKeyCopyExternalRepresentation函数使用未压缩的ANSI X9.63 格式对这些密钥进行编码

我想将这些字节数组转换为Java 中PublicKeyPrivateKey对象。

我在此处(使用 SunJCE)和此处(使用 BouncyCastle)找到的一些示例适用于公钥,但它们没有描述导入私钥的方法。

标签: javaiosswiftcryptographyelliptic-curve

解决方案


04 || X || Y请注意 Apple 文档中的前 65 个字节是如何与私有标量 ( ) 连接的未压缩公钥 ( || K)。去掉这些字节,你就可以创建私钥了。我希望这对某人有所帮助。

/*
 *  For an elliptic curve private key, the output is formatted as the public key
 * concatenated with the big endian encoding of the secret scalar, or 04 || X || Y || K.
 */
private PrivateKey createECPrivateKey(byte[] rawBytes) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidParameterSpecException {
    KeyFactory kf = KeyFactory.getInstance("EC");
    BigInteger s = new BigInteger(Arrays.copyOfRange(rawBytes, 65, rawBytes.length));
    return kf.generatePrivate(new ECPrivateKeySpec(s, ecParameterSpecForCurve("secp256r1")));
}

推荐阅读