Hi I am struggling with encyption / decryption.
My encryption happens here like this:
private static string CreateRequestVerificationToken()
{
var key = System.Configuration.ConfigurationManager.AppSettings["EncryptionKey"];
var unprotectedData = string.Format("{0}|{1}", "A", "B");
var src = Encoding.UTF8.GetBytes(unprotectedData);
using (var aes = new AesCryptoServiceProvider())
{
aes.BlockSize = 128;
aes.KeySize = 128;
aes.Key = Encoding.UTF8.GetBytes(key);
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.Zeros;
aes.GenerateIV();
using (ICryptoTransform encrypt = aes.CreateEncryptor(aes.Key, aes.IV))
{
var crypted = encrypt.TransformFinalBlock(src, 0, src.Length);
return Encoding.UTF8.GetString(crypted);
}
}
}
On the other side the decryption goe like this:
private static string DecryptData(byte[] protectedData)
{
var key = System.Configuration.ConfigurationManager.AppSettings[“EncryptionKey”];
using var aes = Aes.Create();
aes.BlockSize = 128;
aes.KeySize = 128;
aes.Key = Encoding.UTF8.GetBytes(key);
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.Zeros;
aes.GenerateIV();
using ICryptoTransform decrypt = aes.CreateDecryptor(aes.Key, aes.IV);
byte[] decryptedText = decrypt.TransformFinalBlock(protectedData, 0, protectedData.Length);
return Encoding.UTF8.GetString(decryptedText);
}
At the line decrypt.TransformFinalBlock(protectedData, 0, protectedData.Length); I am getting the following error:
System.Security.Cryptography.CryptographicException: The input data is not a complete block. at System.Security.Cryptography.UniversalCryptoDecryptor.UncheckedTransformFinalBlock(ReadOnlySpan1 inputBuffer, Span
1 outputBuffer) at System.Security.Cryptography.UniversalCryptoDecryptor.UncheckedTransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount) at System.Security.Cryptography.UniversalCryptoTransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount)