I am trying to decrypt a string using some pretty standard algorithm.
public static string DecryptString(string cipherText)
{
string keyString = string.Empty;
// Check whether the environment variable exists.
keyString = Environment.GetEnvironmentVariable("EncryptKey");
if (keyString == null)
{
keyString = "E546C8DF278CD5931069B522E695D4F2";
}
var fullCipher = Convert.FromBase64String(cipherText);
using (var aesAlg = Aes.Create())
{
byte[] iv = new byte[aesAlg.BlockSize / 8];
var cipher = new byte[16];
Buffer.BlockCopy(fullCipher, 0, iv, 0, iv.Length);
Buffer.BlockCopy(fullCipher, iv.Length, cipher, 0, iv.Length);
var key = Encoding.UTF8.GetBytes(keyString);
string result;
using (var decryptor = aesAlg.CreateDecryptor(key, iv))
using (var msDecrypt = new MemoryStream(cipher))
using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
using (var srDecrypt = new StreamReader(csDecrypt))
{
result = srDecrypt.ReadToEnd();
}
return result;
}
}
I keep getting the error :
System.Security.Cryptography.CryptographicException: Specified padding mode is not valid for this algorithm.
I have tried multiple ways like this
var iv = new byte[16];
var cipher = new byte[16];
Or
var iv = aesAlg.IV;
I still get an error at this point. What am I doing wrong ?
Now with the help of certificate and master key create SYMMETRIC KEY. Create symmetric key SK1 with algorithm = AES_256 encryption by certificate C1. Once all these KEYs are created in the database, we can use those for encrypting and decrypting data. Below is the script to encrypt the data in the column.
Two changes are required
var cipher = new byte[fullCipher.Length - iv.Length];
and
Buffer.BlockCopy(fullCipher, iv.Length, cipher, 0, fullCipher.Length - iv.Length);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With