目前,我正在尝试将通过 ECDH 生成的一对公钥/私钥(表示为十六进制字符串)传递给importKey
Web Crypto API 的函数。
我从外部源接收这些密钥,但我通过 node.js 生成了类似的密钥进行测试。曲线是prime256v1
。作为参考,我用来测试04b71388fced2daee34793f74a7dfa982e37ce539a728233bcadaec298fc4ee422165b8db13e657f9c7b27b35364f523ad11fab29d717606140cc6312ec2c685cc
的公钥是 ,私钥是4bd22700ec3450b5f27e47ba70c233a680c981ab02c1432a859ae23111bef377
。
const crypto = require('crypto');
const ecdh = crypto.createECDH('prime256v1');
ecdh.generateKeys();
console.log('ecdh p256 pubkey', ecdh.getPublicKey('hex'));
console.log('ecdh p256 prvkey', ecdh.getPrivateKey('hex'));
raw
通过选项成功导入公钥importKey
。
const hexToUintArray = hex => {
const a = [];
for (let i = 0, len = hex.length; i < len; i += 2) {
a.push(parseInt(hex.substr(i, 2), 16));
}
return new Uint8Array(a);
}
const importedKey = await crypto.subtle.importKey(
'raw',
hexToUintArray('04b71388fced2daee34793f74a7dfa982e37ce539a728233bcadaec298fc4ee422165b8db13e657f9c7b27b35364f523ad11fab29d717606140cc6312ec2c685cc'),
{
name: 'ECDH',
namedCurve: 'P-256'
},
true,
[]
);
但是,无法通过相同的方法导入私钥,因为它失败并出现错误DataError: Data provided to an operation does not meet requirements
,因为“原始”选项只接受 EC 公钥。
const importedPrvKey = await crypto.subtle.importKey(
'raw',
hexToUintArray('4bd22700ec3450b5f27e47ba70c233a680c981ab02c1432a859ae23111bef377'),
{
name: 'ECDH',
namedCurve: 'P-256'
},
true,
[]
);
我知道如果它是 JSON Web Key 格式,我可以轻松导入密钥,但我不知道将其从原始格式转换为 JWK 格式或 Web Crypto API 接受的任何其他可导入格式的方法.