.NET Framework RsaCng exception

268 Views Asked by At

I am learning about Cryptography in .NET and I wrote the following function as a test:

byte[] foo(byte[] input, string keyContainerName)
{
   CngKey key = CngKey.Open(keyContainerName);
   RSACng rsa = new RSACng(key);
   rsa.KeySize = 2048;
   byte[] v = rsa.Encrypt(input, RSAEncryptionPadding.OaepSHA512);

   CngKey keyb = CngKey.Open(keyContainerName);
   RSACng rsab = new RSACng(keyb);
   rsab.KeySize = 2048;
   return rsab.Decrypt(v, RSAEncryptionPadding.OaepSHA512);
}

When I try executing it, rsab.Decrypt() throws a Cryptographic exception with the message: "The parameter is incorrect.".

Why is this happening? Where did I go wrong?

P.S. I previously created a key pair in the KSP with CngKey.Create(). foo is called with keyContainerName beeing the keyName passed to CngKey.Create().

1

There are 1 best solutions below

0
On

If you want to create an app that does symmetric and asymmetric encryption and decryption, You can try integrating ExpressSecurity library via NuGet

More info: https://github.com/sangeethnandakumar/Express-Security-Library

AES - Symetric Encryption (For files)

var password = "sangeeth123";
var inputPath = "C:\sample.txt";
var outputPath = "C:\sample.txt.aes";

//AES Encription
AESEncription.AES_Encrypt(inputPath, password);
//AES Description
AESEncription.AES_Decrypt(outputPath, password);

RSA - Asymmetric Encryption (For strings and text)

//Generate Keys
var publicKeyPath = "C:\public_key.rsa";
var privateKeyPath = "C:\private_key.rsa";
RSAEncription.MakeKey(publicKeyPath, privateKeyPath);

var input = "sangeeth"

//RSA Encription
var ciphertext = RSAEncription.EncryptString(input, publicKeyPath);
//RSA Description
input = RSAEncription.DecryptString(ciphertext, privateKeyPath);