I have the code for string encryption/decryption with AES algorithm. Encryption works fine as expected but I could not get correct plain text when I decrypt it back. There must be something wrong in the decryption code.
I have copied the code below.
Please help with this. Thanks.
Below is the encryption and Decryption code.
public static class EncryptionHelper
{
private static int BlockSize = 16;
private static byte[] Key
{
get
{
byte[] hash = SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes("BlahBlahBlah"));
byte[] key = new byte[BlockSize];
Array.Copy(hash, 0, key, 0, BlockSize);
return key;
}
}
private static byte[] IV
{
get
{
StringBuilder builder = new StringBuilder();
Random random = new Random();
for (int i = 0; i < BlockSize; i++)
{
char ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
return Encoding.UTF8.GetBytes(builder.ToString());
}
}
public static string DecodeAndDecrypt(string cipherText)
{
string DecodeAndDecrypt = AesDecrypt(Convert.FromBase64String(HttpUtility.UrlDecode(cipherText)));
return (DecodeAndDecrypt);
}
public static string EncryptAndEncode(string plaintext)
{
return HttpUtility.UrlEncode(Convert.ToBase64String(AesEncrypt(plaintext)));
}
public static string AesDecrypt(Byte[] inputBytes)
{
Byte[] outputBytes = inputBytes;
string plaintext = string.Empty;
using (MemoryStream memoryStream = new MemoryStream(outputBytes))
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, GetCryptoAlgorithm().CreateDecryptor(Key, IV), CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(cryptoStream))
{
plaintext = srDecrypt.ReadToEnd();
}
}
}
return plaintext;
}
public static byte[] AesEncrypt(string inputText)
{
byte[] inputBytes = UTF8Encoding.UTF8.GetBytes(inputText);
for (int i = 0; i < BlockSize; i++)
{
inputBytes[i] ^= IV[i];
}
byte[] result = null;
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, GetCryptoAlgorithm().CreateEncryptor(Key, IV), CryptoStreamMode.Write))
{
cryptoStream.Write(inputBytes, 0, inputBytes.Length);
cryptoStream.FlushFinalBlock();
result = memoryStream.ToArray();
}
}
return result;
}
private static RijndaelManaged GetCryptoAlgorithm()
{
RijndaelManaged algorithm = new RijndaelManaged();
algorithm.Padding = PaddingMode.PKCS7;
algorithm.Mode = CipherMode.CBC;
algorithm.KeySize = 128;
algorithm.BlockSize = 128;
return algorithm;
}
}