三重DES加密
本文关键字:加密 DES 三重 | 更新日期: 2023-09-27 18:04:47
请注意,我在这里遇到的问题是键大小。首先,根据下面代码中的注释,我认为我的密钥需要是24字节(192位)。这没有工作,所以我给了16,32和8字节的键-似乎没有工作。我所说的"不工作"是指在我的文本被加密和解密后,它不具有与原始文本相同的值。
例子:
原文: 'Example test this should work '
加密文本: ¹pÕô6
解密文本: 'Example '
这是我使用的两个函数(加密/解密函数)。我还将包括如何调用每个函数。
// 168-bit (three-key) 3DES (Triple-DES) encrypt a single 8-byte block (ECB mode)
// plain-text should be 8-bytes, key should be 24 bytes.
public byte[] TripleDesEncryptOneBlock(byte[] plainText, byte[] key)
{
// Create a new 3DES key.
TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
// Set the KeySize = 192 for 168-bit DES encryption.
// The msb of each byte is a parity bit, so the key length is actually 168 bits.
des.KeySize = 192;
des.Key = key;
des.Mode = CipherMode.ECB;
des.Padding = PaddingMode.None;
ICryptoTransform ic = des.CreateEncryptor();
byte[] enc = ic.TransformFinalBlock(plainText, 0, 8);
return enc;
}
public byte[] TripleDesDecryptBlock(byte[] plainText, byte[] key)
{
// Create a new 3DES key.
TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
// Set the KeySize = 192 for 168-bit DES encryption.
// The msb of each byte is a parity bit, so the key length is actually 168 bits.
des.KeySize = 192;
des.Key = key;
des.Mode = CipherMode.ECB;
des.Padding = PaddingMode.None;
ICryptoTransform ic = des.CreateDecryptor();
byte[] dec = ic.TransformFinalBlock(plainText, 0, 8);
return dec;
}
// Encrypt Text
textBox5.Text = ByteToString(TripleDesEncryptOneBlock(StringToByte(textBox5.Text), StringToByte("1 2 3 4 5 6 7 8 9 1 1 2 ")));
// Decrypt Text
textBox5.Text = ByteToString(TripleDesDecryptBlock(StringToByte(textBox5.Text), StringToByte("1 2 3 4 5 6 7 8 9 1 1 2 ")));
谢谢你的帮助,
艾凡线索在您正在使用的函数的名称中:TripleDesEncryptOneBlock
此方法只加密输入字符串的一个块(8字节或64位)。要加密整个字符串,您需要将对该方法的多个调用链接起来。
使用
byte[] enc = ic.TransformFinalBlock(plainText, 0, plainText.Length);
我希望它能加密/解密你的整个字符串。此外,您不需要多次调用此方法
你的问题在这里:
byte[] dec = ic.TransformFinalBlock(plainText, 0, 8);
^
你只编码数组的前8个字符,所以当你解码时,只有这8个字符要解码,结果是'Example '
。
如果要对所有文本进行编码,则必须增加该值。但是要小心,如果使用PaddingMode.None
,如果要编码的数组的长度不是8的倍数,它将失败。
我给我的文本添加了一些padding:
int length = plainText.Length / 8;
if(plainText.Length%8 > 0)
{
length++;
}
byte[] paddedText = new byte[length * 8];
plainText.CopyTo(paddedText, 0);
byte[] enc = ic.TransformFinalBlock(paddedText, 0, length * 8);