简体   繁体   中英

DES decryption error “Bad Data” in C# when closing cryptostream

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;
    }

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM