我打算在我的一个项目中使用TripleDES。我正在做一些实验来适应它。我理解三重DES的块大小是8字节所以我假设如果给出8字节的数据,我应该得到8字节的加密数据。但我得到的是:
Input Size | Encrypted Size . | . . | . 6 bytes | 8 bytes 7 bytes | 8 bytes 8 bytes | 16 bytes 9 bytes | 16 bytes . | . . | .
这是正常的吗?这是它应该工作的方式。以下是我尝试使用三重DES的方法:
class TripleDESEncryption
{
private readonly TripleDESCryptoServiceProvider engine;
public TripleDESEncryption () : this (256) { }
public TripleDESEncryption (int keySizeInBits) {
engine = new TripleDESCryptoServiceProvider { KeySize = keySizeInBits };
engine.GenerateKey ();
}
public byte[] Encrypt (byte[] plain) {
return engine.CreateEncryptor ().TransformFinalBlock (plain, 0, plain.Length);
}
public byte[] Decrypt (byte[] encrypted) {
return engine.CreateDecryptor ().TransformFinalBlock (encrypted, 0, encrypted.Length);
}
}
class Program
{
static readonly int MAX_TEXT_LENGTH = 128;
static void Main (string[] args) {
Console.WriteLine ("{0,10}{1,10}{2,10}{3,10}", "Algo", "Key Size", "Input Size", "Encrypted Size");
var tripleDES = new TripleDESEncryption ();
var input = new List<byte> ();
for (int i = 0; i <= MAX_TEXT_LENGTH; i++) {
var plain = input.ToArray ();
var encrypted = tripleDES.Encrypt (plain);
Console.WriteLine ("{0,10}{1,10}{2,10}{3,10}", "Triple DES", keySize, input.Count, encrypted.Length);
input.Add (0x65);
}
Console.ReadLine ();
}
}
class TripleDESEncryption
{
private readonly TripleDESCryptoServiceProvider engine;
public TripleDESEncryption () : this (256) { }
public TripleDESEncryption (int keySizeInBits) {
engine = new TripleDESCryptoServiceProvider { KeySize = keySizeInBits };
engine.GenerateKey ();
}
public byte[] Encrypt (byte[] plain) {
return engine.CreateEncryptor ().TransformFinalBlock (plain, 0, plain.Length);
}
public byte[] Decrypt (byte[] encrypted) {
return engine.CreateDecryptor ().TransformFinalBlock (encrypted, 0, encrypted.Length);
}
}
class Program
{
static readonly int MAX_TEXT_LENGTH = 128;
static void Main (string[] args) {
Console.WriteLine ("{0,10}{1,10}{2,10}{3,10}", "Algo", "Key Size", "Input Size", "Encrypted Size");
var tripleDES = new TripleDESEncryption ();
var input = new List<byte> ();
for (int i = 0; i <= MAX_TEXT_LENGTH; i++) {
var plain = input.ToArray ();
var encrypted = tripleDES.Encrypt (plain);
Console.WriteLine ("{0,10}{1,10}{2,10}{3,10}", "Triple DES", keySize, input.Count, encrypted.Length);
input.Add (0x65);
}
Console.ReadLine ();
}
}
答案 0 :(得分:10)
TripleDESCryptoServiceProvider默认使用PKCS7-padding。这会将任何消息填充到块大小的下一个倍数。
为避免使用填充,只需将Padding
- 属性设置为PaddingMode.None
new TripleDESCryptoServiceProvider {
KeySize = keySizeInBits,
Padding = PaddingMode.None
};