我正在尝试使用导入的 ECDSA key 在浏览器中对字符串文字进行签名。通过粘贴或上传导入我稍后会解决这个问题。我找到了一个 SubtleCrypto 库,它似乎可以完成这项工作,但在遵循他们的示例时,我遇到了 DOM 异常。
我使用的 key 是 prime256v1 ECDSA key 。这是我在 https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey 上的示例中使用的代码
const pemEncodedKey = `-----BEGIN EC PRIVATE KEY-----
base64PrivateKeyHere
-----END EC PRIVATE KEY-----`
const pemHeader = "-----BEGIN EC PRIVATE KEY-----";
const pemFooter = "-----END EC PRIVATE KEY-----";
const pemContents = pemEncodedKey.substring(pemHeader.length, pemEncodedKey.length - pemFooter.length);
const binaryDerString = window.atob(pemContents);
const binaryDer = this.str2ab(binaryDerString);
console.log(await window.crypto.subtle.importKey(
'pkcs8',
binaryDer,
{
name: 'ECDSA',
namedCurve: 'P-256',
},
false,
[ 'sign' ],
))
我哪里出错了?
编辑:添加 str2ab 函数
function str2ab(str) {
const buf = new ArrayBuffer(str.length);
const bufView = new Uint8Array(buf);
for (let i = 0, strLen = str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
最佳答案
原来我正在导入常规 PEM 文件。 PKCS8 PEM 文件略有不同,可以使用以下命令进行转换:
openssl pkcs8 -topk8 -nocrypt -in tradfile.pem -out p8file.pem
根据此处的文档
https://wiki.openssl.org/index.php/Command_Line_Elliptic_Curve_Operations
关于javascript - 将 ECDSA PEM key 导入浏览器进行签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54699523/