I'm trying to decrypt a AES256 coded file but I'm getting a corrupted file output.
I have a 256bit (64 chars) hex AES key and a 128bit (32 chars) hex IV key that I'm converting to byte arrays with the following code.
public byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length / 2;
byte[] bytes = new byte[NumberChars];
using (var sr = new StringReader(hex))
{
for (int i = 0; i < NumberChars; i++)
bytes[i] =
Convert.ToByte(new string(new char[2] { (char)sr.Read(), (char)sr.Read() }), 16);
}
return bytes;
}
The actual code I'm using for decryption is as follows.
public string DecryptCrypt7(byte[] data, string keyString, string ivString)
{
byte[] aesHash = StringToByteArray(keyString);
byte[] ivHash = StringToByteArray(ivString);
try
{
using (var rijndaelManaged = new RijndaelManaged
{
Key = aesHash,
IV = ivHash,
Mode = CipherMode.CBC,
Padding = PaddingMode.None,
BlockSize = 128,
KeySize = 256
})
{
using (var memoryStream = new MemoryStream(data))
{
using (var cryptoStream = new CryptoStream(memoryStream, rijndaelManaged.CreateDecryptor(aesHash, ivHash), CryptoStreamMode.Read))
{
return new StreamReader(cryptoStream).ReadToEnd();
}
}
}
}
catch (CryptographicException e)
{
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
return null;
}
}
It does decrypt the file, but it's clearly corrupted as I can't open it with an sqlite db viewer and see the tables, etc.
Decrypting it via CygWin using OpenSSL with the following command decrypts it properly and I can view all the tables in the file using a viewer.
openssl enc -aes-256-cbc -d -nosalt -nopad -bufsize 16384 -in file.crypt7 -K $(cat aes.txt) -iv $(cat iv.txt) > file.db
The problem is that your original data is binary data, but you're converting it to a string after you've decrypted it. So you just need to change your method to return a byte[]
, then change the end of your decryption method to:
using (Stream encrypted = new MemoryStream(data),
decrypted = new CryptoStream(encrypted,
rijndaelManaged.CreateDecryptor(aesHash, ivHash), CryptoStreamMode.Read),
copy = new MemoryStream())
{
decrypted.CopyTo(copy);
return copy.ToArray();
}
See more on this question at Stackoverflow