我想知道如何解决这个问题。我使用WebCrypto API生成RSA-OAEP密钥对,然后从该密钥对中导出私钥到pkcs8,该私钥以ArrayBuffer形式导出,我想将这个ArrayBuffer编码为base64,以便将其存储为PEM格式。
在这个测试示例中,我将密钥导出为pkcs8,并将此pkcs8重新导入到CryptoKey中。问题是有时它有效,有时却无效。
以下是代码的结果: 注意:只有一种状态发生,而不是同时发生。 注意2:本示例不包含-----BEGIN PRIVATE KEY-----前缀和后缀,我只编码了密钥。
情况1:Uncaught (in promise) URIError: URI malformed(…)b64DecodeUnicode @ try.php:20b64toab @ try.php:70wayBack @ try.php:66(anonymous function) @ try.php:56
情况2:undefined:1 Uncaught (in promise) DOMException
情况3:OK-一路顺畅。
我不知道造成错误的原因,但我认为它与base64编码有关。正如我所说,有时私钥生成得很好,有时则不然。
非常感谢您提前提供的每一份帮助。
在这个测试示例中,我将密钥导出为pkcs8,并将此pkcs8重新导入到CryptoKey中。问题是有时它有效,有时却无效。
以下是代码的结果: 注意:只有一种状态发生,而不是同时发生。 注意2:本示例不包含-----BEGIN PRIVATE KEY-----前缀和后缀,我只编码了密钥。
情况1:Uncaught (in promise) URIError: URI malformed(…)b64DecodeUnicode @ try.php:20b64toab @ try.php:70wayBack @ try.php:66(anonymous function) @ try.php:56
情况2:undefined:1 Uncaught (in promise) DOMException
情况3:OK-一路顺畅。
我不知道造成错误的原因,但我认为它与base64编码有关。正如我所说,有时私钥生成得很好,有时则不然。
非常感谢您提前提供的每一份帮助。
function b64EncodeUnicode(str) {
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
return String.fromCharCode('0x' + p1);
}));
}
function b64DecodeUnicode(str) {
return decodeURIComponent(Array.prototype.map.call(atob(str), function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
}
function addNewLines(str) {
var finalString = '';
for(var i=0; i < str.length; i++) {
finalString += str.substring(0, 64) + '\n';
str = str.substring(64);
}
return finalString;
}
window.crypto.subtle.generateKey(
{
name: "RSA-OAEP",
modulusLength: 2048,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: {name: "SHA-256"}
},
true,
["encrypt", "decrypt"]
).then(function(keyPair) {
window.crypto.subtle.exportKey(
"pkcs8",
keyPair.privateKey
).then(function(exportedPrivateKey) {
var byteArray = new Uint8Array(exportedPrivateKey);
console.log(byteArray);
var byteString = '';
for(var i=0; i < byteArray.byteLength; i++) {
byteString += String.fromCodePoint(byteArray[i]);
}
wayBack(addNewLines(b64EncodeUnicode(byteString)));
});
});
function wayBack(pem) {
var lines = pem.split('\n');
var encodedString = '';
for(var i=0; i < lines.length; i++) {
encodedString += lines[i].trim();
}
b64toab(encodedString);
}
function b64toab(b64) {
var byteString = b64DecodeUnicode(b64);
console.log(byteString);
var byteArray = new Uint8Array(byteString.length);
for(var i=0; i < byteString.length; i++) {
byteArray[i] = byteString.codePointAt(i);
}
console.log(byteArray);
window.crypto.subtle.importKey(
"pkcs8",
byteArray,
{
name: "RSA-OAEP",
hash: {name: "SHA-256"}
},
true,
["decrypt"]
).then(function(importedPrivateKey) {
console.log(importedPrivateKey);
});
}