java - 在 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 中PublicKey
的PrivateKey
对象。
我在此处(使用 SunJCE)和此处(使用 BouncyCastle)找到的一些示例适用于公钥,但它们没有描述导入私钥的方法。
解决方案
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")));
}
推荐阅读
- c - 请运行这段代码并告诉我为什么会得到这个结果
- python - 子类化字符串并让 MyPy 开心
- c# - WPF DataGrid 绑定到列表和子列表
- flutter - Flutter - 通过整个应用程序监听一个值
- javascript - 将数组转换为迭代器
- java - 如何在 CUBA 平台中使用按钮打开选项卡表的特定选项卡?
- php - Divi Theme Builder 不断加载
- amazon-web-services - 如何 SAM 使用项目目录中的初始文件部署 AWS::S3::Bucket
- oracle - 为什么 sql developer(oracle) 中的实时 SQL 监视器让我没有选择?在 sql developer 中查看性能指标的步骤是什么?
- jasper-reports - Jasper 报告 - 获取重复记录