I was able to put together a encryption sample like below but during decryption i get invalid data(Exception). How am i supposed to decrypt
public static string EncryptWithAes(string plainText, byte[] key, byte[] initiationVector)
{
byte[] cryptoBytes = Encoding.UTF8.GetBytes(plainText);
using (RijndaelManaged aesAlgorithm = new RijndaelManaged())
{
aesAlgorithm.Key = key;
aesAlgorithm.IV = initiationVector;
aesAlgorithm.Mode = CipherMode.ECB;
using (ICryptoTransform encryptoTransform = aesAlgorithm.CreateEncryptor(aesAlgorithm.Key, aesAlgorithm.IV))
{
cryptoBytes = encryptoTransform.TransformFinalBlock(cryptoBytes, 0, cryptoBytes.Length);
}
}
return Convert.ToBase64String(cryptoBytes);
}
public static string DecryptAesCryptoString(string cipherText, byte[] key, byte[] initiationVector)
{
byte[] decryptedByte;
using (RijndaelManaged aesAlgorithm = new RijndaelManaged())
{
aesAlgorithm.Key = key;
aesAlgorithm.IV = initiationVector;
aesAlgorithm.Mode = CipherMode.ECB;
using (ICryptoTransform decryptoTransform = aesAlgorithm.CreateDecryptor(aesAlgorithm.Key, aesAlgorithm.IV))
{
byte[] cipherBytes = Convert.FromBase64String(cipherText);
decryptedByte = decryptoTransform.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length);
}
}
return Encoding.UTF8.GetString(decryptedByte);
}
i think the problem is with all the encoding that are going inside these methods
plainText = stackoverflow
base64encoded Key = B8Y/6doxwqU870C6jzYWhsr3hKSLokAOkkLCDiy+TS4=
(should be easy to convert to bytes ain't it)
base64encoded IV = NZIpD60eBmdsOFFhA2bfvw==
encryptedValue = 77+977+977+977+977+9Ce+/ve+/vQ3vv70F77+9UzHvv73vv70=
I provide same encrypted value , IV and Key to decrypt to Stackoverflow
and sadly this was certainly due to the Encoding problem. Now solved it like below
public static string EncryptWithAes(string plainText, byte[] key, byte[] initiationVector)
{
byte[] cryptoBytes = Convert.FromBase64String(plainText);
using (RijndaelManaged aesAlgorithm = new RijndaelManaged())
{
aesAlgorithm.Key = key;
aesAlgorithm.IV = initiationVector;
aesAlgorithm.Mode = CipherMode.ECB;
using (ICryptoTransform encryptoTransform = aesAlgorithm.CreateEncryptor(aesAlgorithm.Key, aesAlgorithm.IV))
{
cryptoBytes = encryptoTransform.TransformFinalBlock(cryptoBytes, 0, cryptoBytes.Length);
}
}
return Convert.ToBase64String(cryptoBytes);
}
public static string DecryptAesCryptoString(string cipherText, byte[] key, byte[] initiationVector)
{
byte[] decryptedByte;
using (RijndaelManaged aesAlgorithm = new RijndaelManaged())
{
aesAlgorithm.Key = key;
aesAlgorithm.IV = initiationVector;
aesAlgorithm.Mode = CipherMode.ECB;
using (ICryptoTransform decryptoTransform = aesAlgorithm.CreateDecryptor(aesAlgorithm.Key, aesAlgorithm.IV))
{
byte[] cipherBytes = Convert.FromBase64String(cipherText);
decryptedByte = decryptoTransform.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length);
}
}
return Convert.ToBase64String(decryptedByte);
}