diafygi/webcrypto-examples

Issue in decryption crypto.subtle encrypted text using RSACryptoServiceProvider

kadandap opened this issue · 0 comments

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!