tripleDES decryption c#

本文关键字:decryption tripleDES | 更新日期: 2023-09-27 18:14:57

我得到了一个经过加密和编码的tripleDES base64字符串:

ABvAsOKcGXqc5uQ4O5Z53isJaH31Pa8 + PeddljE4mSU =

我还得到:

key size = 128;

key = 0123456789ABCDEF

iv = ABCDEFGH

我已经写出了下面的代码。我一直得到一个异常扔给我说"坏PKCS7填充。无效长度31"我在某个地方丢失了一个字节。谁能告诉我我做错了什么?

string base64Encoded = "ABvAsOKcGXqc5uQ4O5Z53isJaH31Pa8+PeddljE4mSU="; // 
string ASCIIkey = "0123456789ABCDEF";
string ASCIIiv = "ABCDEFGH";

TripleDESCryptoServiceProvider tDES = new TripleDESCryptoServiceProvider();
tDES.KeySize = 128;
tDES.BlockSize = 64;
tDES.Padding = PaddingMode.PKCS7;
tDES.Mode = CipherMode.ECB;
tDES.Key = Encoding.ASCII.GetBytes(ASCIIkey);
tDES.IV = Encoding.ASCII.GetBytes (ASCIIiv);
byte[] encryptedData = Convert.FromBase64String(base64Encoded);
ICryptoTransform transform = tDES.CreateDecryptor();
byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
string message = System.Text.Encoding.ASCII.GetString(plainText);
Console.Write (message);

tripleDES decryption c#

With

tDES.Mode = CipherMode.CBC;

,并使用HashAlgorithm.TransformBlock作为参考样本(见PrintHashMultiBlock)

int offset = 0;
while(encryptedData.Length - offset >= size)
    offset += transform.TransformBlock(encryptedData, offset,
                                       encryptedData.Length - offset,
                                       outputBuffer, offset);

我能得到一个已知的短语

你所有的基地都属于我们!


但是,更好的方法是只更改两行
tDES.Padding = PaddingMode.None;  // instead of PaddingMode.PKCS7
tDES.Mode = CipherMode.CBC;       // instead of CipherMode.ECB

这是由@MaartenBodewes建议的。

因此,请随意拒绝接受答案,并删除重复的:-)。