我正在使用 Web Crypto,更具体地说,这些示例:https ://github.com/diafygi/webcrypto-examples/#rsa-oaep
我的主要目标是用我的公钥加密一个字符串并用我的私钥解密它。
公钥加密效果很好,但是当我尝试用私钥解密加密字符串时,它返回以下错误:OperationError
以及一个空字符串。
我正在使用以下功能:
function encryptDataWithPublicKey(data, key) {
data = stringToArrayBuffer(data);
return window.crypto.subtle.encrypt(
{
name: "RSA-OAEP",
//label: Uint8Array([...]) //optional
},
key, //from generateKey or importKey above
data //ArrayBuffer of data you want to encrypt
);
}
function decryptDataWithPrivateKey(data, key) {
data = stringToArrayBuffer(data);
return window.crypto.subtle.decrypt(
{
name: "RSA-OAEP",
//label: Uint8Array([...]) //optional
},
key, //from generateKey or importKey above
data //ArrayBuffer of data you want to encrypt
);
}
function stringToArrayBuffer(str){
var buf = new ArrayBuffer(str.length);
var bufView = new Uint8Array(buf);
for (var i=0, strLen=str.length; i<strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
更新
var data = "example";
encryptDataWithPublicKey(data, publicKey).then((result) => {
var rdata = arrayBufferToString(result);
return decryptDataWithPrivateKey(rdata, privateKey).then((result) => {
var result = arrayBufferToString(result);
});
});
function arrayBufferToString(str){
var byteArray = new Uint8Array(str);
var byteString = '';
for(var i=0; i < byteArray.byteLength; i++) {
byteString += String.fromCodePoint(byteArray[i]);
}
return byteString;
}