Reading from a CryptoStream results in a padding error - c#

I'm writing an Aes decryption method and currently, I'm stuck on trying to read all the contents inside my CryptoStream and put it all into a byte[]. This is what I have for decryption:
public byte[] GetDecrypted()
{
byte[] toReturn;
using (Aes dec = Aes.Create())
{
dec.Key = Key;
dec.IV = IV;
ICryptoTransform cryptoTransform = dec.CreateDecryptor(dec.Key, dec.IV);
using (MemoryStream ms = new MemoryStream(Data))
{
using (CryptoStream cs = new CryptoStream(ms, cryptoTransform, CryptoStreamMode.Read))
{
using (MemoryStream decMs = new MemoryStream())
{
cs.CopyTo(decMs);
toReturn = decMs.ToArray();
}
}
}
}
return toReturn;
}
For encryption, I used very similar code; maybe something's wrong here:
public byte[] GetEncrypted()
{
byte[] toReturn;
using (Aes enc = Aes.Create())
{
enc.Key = Key;
enc.GenerateIV();
IV = enc.IV;
ICryptoTransform cryptoTransform = enc.CreateEncryptor(enc.Key, enc.IV);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, cryptoTransform, CryptoStreamMode.Write))
{
cs.Write(Data, 0, Data.Length);
toReturn = ms.ToArray();
}
}
}
return toReturn;
}

Your problem indeed lies in your encrypt side. You must close the crypto stream to flush the data out to the underlying stream first. It is a easy fix, just move your .ToArray() outside of CryptoStream's using block.
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, cryptoTransform, CryptoStreamMode.Write))
{
cs.Write(Data, 0, Data.Length);
}
toReturn = ms.ToArray();
}

Related

Why does my AES-decrypted data have garbage bytes at the end?

I'm trying to use AesCryptoProvider to encrypt and decrypt byte arrays.
Here are my encrypt and decrypt methods:
public static byte[] EncryptAes(byte[] data, out byte[] key, out byte[] iv)
{
if (data == null || data.Length <= 0)
throw new ArgumentNullException("data");
try
{
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.KeySize = 256;
aesAlg.BlockSize = 128;
aesAlg.Padding = PaddingMode.PKCS7;
aesAlg.Mode = CipherMode.CBC;
aesAlg.GenerateKey();
aesAlg.GenerateIV();
key = aesAlg.Key;
iv = aesAlg.IV;
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, aesAlg.CreateEncryptor(), CryptoStreamMode.Write))
{
csEncrypt.Write(data, 0, data.Length);
}
return msEncrypt.ToArray();
}
}
}
catch (CryptographicException e)
{
Log.Error(e);
key = null;
iv = null;
return null;
}
}
public static byte[] DecryptAes(byte[] encryptedData, byte[] key, byte[] iv)
{
if (encryptedData == null || encryptedData.Length <= 0)
throw new ArgumentNullException("encryptedData");
if (key == null || key.Length <= 0)
throw new ArgumentNullException("key");
if (iv == null || iv.Length <= 0)
throw new ArgumentNullException("iv");
try
{
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.KeySize = 256;
aesAlg.BlockSize = 128;
aesAlg.Padding = PaddingMode.PKCS7;
aesAlg.Mode = CipherMode.CBC;
aesAlg.Key = key;
aesAlg.IV = iv;
using (MemoryStream msDecrypt = new MemoryStream(encryptedData))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, aesAlg.CreateDecryptor(), CryptoStreamMode.Write))
{
csDecrypt.Write(encryptedData, 0, encryptedData.Length);
}
return msDecrypt.ToArray();
}
}
}
catch (CryptographicException e)
{
Log.Error(e);
return null;
}
}
Then to test it, I'm using this code:
originalMessage = "This is a test message.";
originalData = System.Text.Encoding.UTF8.GetBytes(originalMessage);
byte[] key, iv;
byte[] encryptedData = Encryption.EncryptAes(originalData, out key, out iv);
byte[] decryptedData = Encryption.DecryptAes(encryptedData, key, iv);
string decryptedMessage = System.Text.Encoding.UTF8.GetString(decryptedData);
Log.Debug(decryptedMessage); // This is a test message.?{?o?}??
The log output shows that the decrypted message has a bunch of garbage characters "?{?o?}??" at the end.
I've seen similar questions, but their answers don't seem to help. I've tried writing to another array during decryption like this:
using (MemoryStream msDecrypt = new MemoryStream(encryptedData))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, aesAlg.CreateDecryptor(), CryptoStreamMode.Write))
{
byte[] decryptedData = new byte[encryptedData.Length];
csDecrypt.Write(decryptedData, 0, decryptedData.Length);
}
return msDecrypt.ToArray();
}
But that results in this exception:
System.Security.Cryptography.CryptographicException: Padding is invalid and cannot be removed.
So there's gotta be something I'm missing. Any ideas? Thanks!
Yeah, reusing buffers is biting you. You generally don't expect the encrypted and decrypted data to be the same sizes, so reusing a buffer causes you to see left-over encrypted data in the decrypted data.
Make your decrypt similar to encrypt. Don't pass the buffer to the constructor of MemoryStream, let it allocate a buffer of the correct size:
using (MemoryStream msDecrypt = new MemoryStream())
{
using (CryptoStream csDecrypt =
new CryptoStream(msDecrypt,
aesAlg.CreateDecryptor(),
CryptoStreamMode.Write))
{
csDecrypt.Write(encryptedData, 0, encryptedData.Length);
}
return msDecrypt.ToArray();
}
I've tried writing to another array during decryption like this:
using (MemoryStream msDecrypt = new MemoryStream(encryptedData))
{
using (CryptoStream csDecrypt =
new CryptoStream(msDecrypt,
aesAlg.CreateDecryptor(),
CryptoStreamMode.Write))
{
byte[] decryptedData = new byte[encryptedData.Length];
csDecrypt.Write(decryptedData, 0, decryptedData.Length);
}
return msDecrypt.ToArray();
}
No read it back to yourself. You're still configuring the cryptostream to write rather than read. What you're doing here is allocating a new buffer and then telling AES to decrypt that empty buffer into the memory stream which was initialized with the encrypted data.

Encrypting and Decrypting a file with AES generates a broken file

I'm trying to encrypt and decrypt a file using AES. The problem that I have is that when the file gets decrypted, it is broken and you can't open it. The original file has a length of 81.970 bytes and the decrypted file has a length of 81.984 bytes...so there are 14 bytes added for some reason. The problem could be in the way the file gets encrypted but I don't know what I'm doing wrong.
What am I missing here? Could it be the way I'm processing the password, the iv and the padding?
Thanks for your time!
This is the code I use to encrypt:
private AesManaged aesManaged;
private string filePathToEncrypt;
public Encrypt(AesManaged aesManaged, string filePathToEncrypt)
{
this.aesManaged = aesManaged;
this.filePathToEncrypt = filePathToEncrypt;
}
public void DoEncryption()
{
byte[] cipherTextBytes;
byte[] textBytes = File.ReadAllBytes(this.filePathToEncrypt);
using(ICryptoTransform encryptor = aesManaged.CreateEncryptor(aesManaged.Key, aesManaged.IV))
using (MemoryStream ms = new MemoryStream())
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
cs.Write(textBytes, 0, textBytes.Length);
cs.FlushFinalBlock();
cipherTextBytes = ms.ToArray();
}
File.WriteAllBytes("EncryptedFile.aes", cipherTextBytes);
}
This is the code I use to decrypt:
private AesManaged aesManaged;
private string filePathToDecrypt;
public Decrypt(AesManaged aesManaged, string filePathToDecrypt)
{
this.aesManaged = aesManaged;
this.filePathToDecrypt = filePathToDecrypt;
}
public void DoDecrypt()
{
byte[] cypherBytes = File.ReadAllBytes(this.filePathToDecrypt);
byte[] clearBytes = new byte[cypherBytes.Length];
ICryptoTransform encryptor = aesManaged.CreateDecryptor(aesManaged.Key, aesManaged.IV);
using (MemoryStream ms = new MemoryStream(cypherBytes))
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Read))
{
cs.Read(clearBytes, 0, clearBytes.Length);
clearBytes = ms.ToArray();
}
File.WriteAllBytes("DecryptedFile.gif", clearBytes);
}
And here is how I call the functions:
string filePathToEncrypt = "dilbert.gif";
string filePathToDecrypt = "EncryptedFile.aes";
string password = "Password";
string passwordSalt = "PasswordSalt";
Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(password, Encoding.ASCII.GetBytes(passwordSalt));
var aesManaged = new AesManaged
{
Key = deriveBytes.GetBytes(128 / 8),
IV = deriveBytes.GetBytes(16),
Padding = PaddingMode.PKCS7
};
Console.WriteLine("Encrypting File...");
var encryptor = new Encrypt(aesManaged, filePathToEncrypt);
encryptor.DoEncryption();
Thread.Sleep(300);
Console.WriteLine("Decrypting File...");
var decryptor = new Decrypt(aesManaged, filePathToDecrypt);
decryptor.DoDecrypt();
Thread.Sleep(300);
Try with:
public void DoEncryption()
{
byte[] cipherBytes;
byte[] textBytes = File.ReadAllBytes(this.filePathToEncrypt);
using (ICryptoTransform encryptor = aesManaged.CreateEncryptor(aesManaged.Key, aesManaged.IV))
using (MemoryStream input = new MemoryStream(textBytes))
using (MemoryStream output = new MemoryStream())
using (CryptoStream cs = new CryptoStream(output, encryptor, CryptoStreamMode.Write))
{
input.CopyTo(cs);
cs.FlushFinalBlock();
cipherBytes = output.ToArray();
}
File.WriteAllBytes("EncryptedFile.aes", cipherBytes);
}
and
public void DoDecrypt()
{
byte[] cypherBytes = File.ReadAllBytes(this.filePathToDecrypt);
byte[] textBytes;
using (ICryptoTransform decryptor = aesManaged.CreateDecryptor(aesManaged.Key, aesManaged.IV))
using (MemoryStream input = new MemoryStream(cypherBytes))
using (MemoryStream output = new MemoryStream())
using (CryptoStream cs = new CryptoStream(input, decryptor, CryptoStreamMode.Read))
{
cs.CopyTo(output);
textBytes = output.ToArray();
}
File.WriteAllBytes("DecryptedFile.gif", textBytes);
}
Note that the code could be modified to not use temporary byte[] and read/write directly to input/output streams.
In general you can't desume the length of the plaintext from the length of the cyphertext, so this line:
new byte[cypherBytes.Length]
was totally wrong.
And please, don't use Encoding.ASCII in 2016. It is so like previous century. Use Encoding.UTF8 to support non-english characters.
The answer may be very simple. I don't see where do u try to choose a cipher mode, so by default it probably takes CBC, as IV was inited. Then, 81.970 are padded by 14 bytes, to be divisible by 32. So when it happens, the memory you allocated was just 81.970, so the padding bytes doesn't write correctly, cause of some sort of memory leak, and when decrypt is started, unpadding doesn't work correctly.

small file cause OutofMemoryException

I have an encrypted file which I decrypt first and then try to deserialize it using memorystream and binaryformatter but when I try to assign deserialized files to a list I catch OutOfMemoryException (file is really small - 17KB)
here is the code
byte[] encryptedData = File.ReadAllBytes(fileName);
byte[] result = Decrypt(Algo, key, vector, encryptedData) ;
BinaryFormatter ser = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream(result)) {
try {
files = ser.Deserialize(ms) as List<IItem>;
} catch (OutOfMemoryException) {
} catch (SerializationException) {
MessageBox.Show("Incorrect password!");
return;
}
}
files = ser.Deserialize(ms) as List<IItem>; - this what cause exception
encrypted file size 1696
after decryption 1691 - normal size.
here Decryption code
public byte[] Decode(byte[] data)
{
string key = ASCIIEncoding.ASCII.GetString(rc2.Key);
string IV = ASCIIEncoding.ASCII.GetString(rc2.IV);
ICryptoTransform decryptor = rc2.CreateDecryptor(rc2.Key,rc2.IV);
StringBuilder roundtrip = new StringBuilder();
using (MemoryStream msDecrypt = new MemoryStream(data))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
int b = 0;
do
{
b = csDecrypt.ReadByte();
if (b != -1)
{
roundtrip.Append((char) b);
}
} while (b != -1);
}
}
byte[] decrypted = ASCIIEncoding.ASCII.GetBytes(roundtrip.ToString());
return decrypted;
}
#MineR and #HansPassant was right problem was in using chars while decrypting)) i have changed my code
public byte[] Decode(byte[] data)
{
ICryptoTransform decryptor = rc2.CreateDecryptor(rc2.Key,rc2.IV);
byte[] decrypted = new byte[data.Length];
using (MemoryStream msDecrypt = new MemoryStream(data))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
csDecrypt.Read(decrypted, 0, data.Length);
}
}
return decrypted;
}
and now it works. Thx all for answers.

AES Encryption - Encrypt Bytes

I am trying to encrypt bytes with Aes. However, the output I get is really weird. Here is my functions (encrypt and decrypt). Am I doing something wrong?
public static byte[] encryptStream(byte[] plain, byte[] Key, byte[] IV)
{
byte[] encrypted; ;
using (MemoryStream mstream = new MemoryStream())
{
using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
{
using (CryptoStream cryptoStream = new CryptoStream(mstream,
aesProvider.CreateEncryptor(Key, IV), CryptoStreamMode.Write))
{
cryptoStream.Write(plain, 0, plain.Length);
}
}
encrypted = mstream.ToArray();
}
return encrypted;
}
public static byte[] decryptStream(byte[] encrypted, byte[] Key, byte[] IV)
{
byte[] plain;
using (MemoryStream mStream = new MemoryStream())
{
using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
{
using (CryptoStream cryptoStream = new CryptoStream(mStream,
aesProvider.CreateDecryptor(Key, IV), CryptoStreamMode.Read))
{
cryptoStream.Read(encrypted, 0, encrypted.Length);
}
}
plain = mStream.ToArray();
}
return plain;
}
The issue is in your decryptStream() method, when you read from the cryptoStream you read INTO the encrypted buffer. When you call Read() you are already reading from the encrypted buffer because you wrapped it with the memory stream. You want to read into a NEW buffer which concatenated together will be the decrypted bytes.
public static byte[] decryptStream(byte[] encrypted, byte[] Key, byte[] IV)
{
byte[] plain;
byte[] buffer = new byte[32768];
int totalRead = 0;
MemoryStream plainStream = new MemoryStream();
using (MemoryStream mStream = new MemoryStream(encrypted))
{
using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
{
using (CryptoStream cryptoStream = new CryptoStream(mStream,
aesProvider.CreateDecryptor(Key, IV), CryptoStreamMode.Read))
{
while (true)
{
int read = cryptoStream.Read(buffer, 0, encrypted.Length);
if (read == 0)
break;
else
plainStream.Write(buffer, totalRead, read);
totalRead += read;
}
}
}
plain = plainStream.ToArray();
}
return plain;
}

How to return byte[] when decrypt using CryptoStream (DESCryptoServiceProvider)

This is a beginner question,
Every time I search on the internet, decrypt with DESCryptoServiceProvider function always returning a string.
How can we get byte[] for the return?
This is the code. Thank you for any help.
DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
cryptoProvider.Padding = PaddingMode.None;
cryptoProvider.Mode = CipherMode.CBC;
MemoryStream memoryStream = new MemoryStream(value);
CryptoStream cryptoStream = new CryptoStream(memoryStream,
cryptoProvider.CreateDecryptor(password, initVector), CryptoStreamMode.Read);
StreamReader reader = new StreamReader(cryptoStream);
return reader.ReadToEnd();
//how to return byte[];
I had this problem too, and I created a class with some functions to help me with this issues.
The function to perform the cryptography is:
private byte[] PerformCryptography(ICryptoTransform cryptoTransform, byte[] data)
{
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write))
{
cryptoStream.Write(data, 0, data.Length);
cryptoStream.FlushFinalBlock();
return memoryStream.ToArray();
}
}
}
The ICryptoTransform is either a spezific encryptor or decryptor.
This Method works for symmetric altorithm's
Just for example, the methods for encryption and decryption look like:
public byte[] Encrypt(byte[] data)
{
if (CanPerformCryptography(data))
{
using (var encryptor = _algorithm.CreateEncryptor(_key, _iv))
{
return PerformCryptography(encryptor, data);
}
}
return data;
}
public byte[] Decrypt(byte[] data)
{
if (CanPerformCryptography(data))
{
using (var decryptor = _algorithm.CreateDecryptor(_key, _iv))
{
return PerformCryptography(decryptor, data);
}
}
return data;
}

Categories

Resources