Reputation: 167
I try to decrypt an encrypted byte array (encrypt with K1 and decrypt with K2). Visual Studio throws an exception "BAD DATA" when it tries to close my crypto stream
here's my code snippet of DES decryption
public Byte[] Decrypt(Byte[] cipherData, Byte[] key, Byte[] iv)
{
MemoryStream ms = new MemoryStream();
DES mDES = DES.Create();
mDES.Key = key;
mDES.IV = iv;
mDES.Padding = PaddingMode.PKCS7;
CryptoStream cs = new CryptoStream(ms, mDES.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(cipherData, 0, cipherData.Length);
cs.Close();
Byte[] decryptedData = ms.ToArray();
return decryptedData;
}
the initial vector is the same as encryption. I don't know why this error occurred.
Added: As recommended by Greg B, I post here my code snippet of encryption. The output of encryption is the input of decryption (two different keys)
public Byte[] Decrypt(Byte[] cipherData, Byte[] key, Byte[] iv)
{
MemoryStream ms = new MemoryStream();
DES mDES = DES.Create();
mDES.Key = key;
mDES.IV = iv;
mDES.Padding = PaddingMode.PKCS7;
CryptoStream cs = new CryptoStream(ms, mDES.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(cipherData, 0, cipherData.Length);
cs.Close();
Byte[] decryptedData = ms.ToArray();
return decryptedData;
}
Upvotes: 1
Views: 5438
Reputation: 10257
the problem you encountered comes from the selected padding mode.
since padding is used when decrypting your cipher text the cryptostream tries to remove the padding when your retrieve the decrypted bytes. since you don't use the key the data was encrypted with, you will get "garbage" ... the cryptostream fails to detect the padding that needs to be removed, and the operation fails with the observed exception.
if you want to rebuld someething like 3DES with the DES class use PaddingMode NONE for your decryption and the following encryption step (so only the first encryption or the last decryption uses padding)
Upvotes: 3