最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Encrypt and Decrypt with RSA OAEP - Stack Overflow

programmeradmin1浏览0评论

I'm using Web Crypto, more specifically these examples:

My main goal is to encrypt a string with my public key and decrypt it with my private key.

The public key encryption works well but when I try to decrypt the encrypted string with the private key, it returns the following error: OperationError and a empty string as well.

I'm using the following functions:

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;
}

UPDATE

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;
}

I'm using Web Crypto, more specifically these examples: https://github./diafygi/webcrypto-examples/#rsa-oaep

My main goal is to encrypt a string with my public key and decrypt it with my private key.

The public key encryption works well but when I try to decrypt the encrypted string with the private key, it returns the following error: OperationError and a empty string as well.

I'm using the following functions:

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;
}

UPDATE

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;
}
Share Improve this question edited Jan 10, 2017 at 18:11 bartonjs 33.3k4 gold badges82 silver badges126 bronze badges asked Jan 10, 2017 at 1:33 urburb 9641 gold badge14 silver badges31 bronze badges 7
  • 1 you say you are encrypting the data, then decrypting it ... you've shown the functions that do that, but you haven't shown how you use them - perhaps you are using them wrong (i.e. what are you doing with the return value from your encrypt/decrypt functions) – Jaromanda X Commented Jan 10, 2017 at 1:36
  • The encryptDataWithPublicKey works well, but I can't decrypt it with the other function. I can't understand why. – urb Commented Jan 10, 2017 at 1:38
  • yes, so you already said in the question ... but I asked you to show how you are using your functions, because I suspect you are doing it wrong, I didn't ask this to waste your time or anything – Jaromanda X Commented Jan 10, 2017 at 1:40
  • 1 Yeah, I get the feeling the issue is in arrayBufferToString and stringToArrayBuffer conversion ... but I can't put a finger on it – Jaromanda X Commented Jan 10, 2017 at 1:51
  • 1 Most systems encode the cipher text from raw bytes to hexadecimal or Base64 encoding for transportability and stability (you'll get a "safe" string like 54686973206973206120706c61696e74657874206d6573736167652e0a or VGhpcyBpcyBhIHBsYWludGV4dCBtZXNzYWdlLgo=). Then just decode that string before decrypting the raw bytes. – Andy Commented Jan 10, 2017 at 3:52
 |  Show 2 more ments

1 Answer 1

Reset to default 4

The code included in your question is correct, so the issue will be in the hidden part. I just added window.crypto.subtle.generateKey to your code to generate the RSA-OAEP keys and works

Please, take a look to the full example

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;
}

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;
}

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
    );
}


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) {

    var data = "example";
    encryptDataWithPublicKey(data, keyPair.publicKey).then((result) => {
        var rdata = arrayBufferToString(result);
        return decryptDataWithPrivateKey(rdata, keyPair.privateKey).then((result) => {
            var result = arrayBufferToString(result);
            console.log(result);
        });
    });
}).catch (function (err){
    console.log(err);
});
发布评论

评论列表(0)

  1. 暂无评论