diafygi / webcrypto-examples

Web Cryptography API Examples Demo: https://diafygi.github.io/webcrypto-examples/
GNU General Public License v2.0
1.65k stars 194 forks source link

Issue in decryption crypto.subtle encrypted text using RSACryptoServiceProvider #62

Open kadandap opened 5 years ago

kadandap commented 5 years ago

Hi,

I am trying to use RSA public key using RSACryptoServiceProvider and use it for encryption through window.crypto.subtle but ending with Cryptography_OAEPDecoding upon decryption.

//Generating public key:

        var cspParams = new CspParameters { KeyContainerName = containerName };

        using (var rsa = new RSACryptoServiceProvider(cspParams))
        {                
            var rsaparameters = rsa.ExportParameters(true);

            var base64ModulusKey =  GetModulusKey(rsaparameters);

            return base64ModulusKey;
        }

Encryption through window.crypto.subtle:

var jwk_base64 = base64ModulusKey.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, '');

window.crypto.subtle.importKey(
    "jwk",
    {   
        kty: "RSA",
        e: "AQAB",            
        n: jwk_base64,
        alg: "RSA-OAEP-256",            
        ext: true,
    },
    { name: "RSA-OAEP", hash: { name: "sha-256" } },            
    false,
    ["encrypt"]);

window.crypto.subtle.encrypt(
    {          
      name: "RSA-OAEP"          
    },          
    cryptoKey,                         
    inputMessageBytes              
  ).then(function(encrypted){        
    console.log("base64 encrypted text: " + arrayToBase64String(new Uint8Array(encrypted)));
}); 

//Decryption using private key:

        using (var rsa = new RSACryptoServiceProvider(cspParams))
        {
            decryptedBytes = rsa.Decrypt(encryptedBytes, true);                
        } 

Thanks in advance!