这是我的问题:我有一个 C++ 遗留代码(使用 crypto++ v5.6.1),并且我用 C# 开发了一个新代码(使用 System.Security.Cryptography 的 .NET 3.5)。我无法改变C++ 代码,但我需要能够解密之前加密的数据,并且以前的应用程序必须能够解密我将使用新的 C# 代码加密的数据。
两种情况使用的算法都是 TripleDES 和 CFB 加密模式,但最终加密的数据并不相同,字节数以及第一个字节都相同,但除此之外所有其他字节都不同。
填充是在 C++ 代码中手动完成的(添加零)。所以我将 PaddingValue 设置为 PaddingMode.Zeros。 (我还尝试在 C# 代码中手动在末尾添加零,它没有改变任何内容)。
我尝试使用不同的 System.Text.Encoding 但结果是相同的(实际上测试的字符是“纯”ASCII(即:0 和 126 之间))。
在 C++ 代码中,MandatoryBlockSize() 的值为 8,因此我也将 FeedbackSize 设置为 8。但如果我理解它的写法,它实际上就是我的静脉注射的大小,不是吗?
密钥大小为 24 字节(3 个不同的密钥),IV 长为 8 字节。两个代码中它们是相同的。
如果我在两种情况下都使用 CBC 模式,结果是相同的(但是,正如我所说,我无法更改遗留代码...),OFB 和 CTS 模式会抛出异常(其中一种不可用,另一种不兼容)在我的 .NET 应用程序上,所以我无法比较结果。
我尝试使用 Mono(.Net 版本 3.5 和 4.0),或使用 Visual(.Net 3.5 或 4.0),4 个加密结果是相同的,但与原始结果不同。
现在我真的不知道要测试什么...我不想将 Crypto++ 包装在 C++/CLI 项目中来使用它而不是 System.Security.Cryptography。
有人有建议或者可以告诉我我做错了什么吗?
这是 C++ 代码:
void *CryptData(BYTE *bDataIn, LONG lIn, LONG *lOut, byte* key, byte* iv)
{
byte *bIn;
byte *bOut;
LONG l2,lb;
CFB_FIPS_Mode<DES_EDE3>::Encryption encryption_DES_EDE3_CFB;
encryption_DES_EDE3_CFB.SetKeyWithIV(key, sizeof(key), iv, sizeof(iv));
lb = encryption_DES_EDE3_CFB.MandatoryBlockSize();
l2 = ((lIn + lb - 1)/lb)*lb;
bIn = (byte*)malloc(l2);
bOut = (byte*)malloc(l2);
memset(bIn,0,l2);
memset(bOut,0,l2);
memcpy(bIn,bDataIn,lIn);
encryption_DES_EDE3_CFB.ProcessString(bOut, bIn, l2);
*lOut = l2;
return bOut;
}
这是 C# 代码:
public FibxCrypt()
{
_cryptoAlgo = new TripleDESCryptoServiceProvider();
//_cryptoAlgo.GenerateKey();
_cryptoAlgo.Key = _key;
//_cryptoAlgo.GenerateIV();
_cryptoAlgo.IV = _iv;
_cryptoAlgo.Mode = CipherMode.CFB;
_cryptoAlgo.Padding = PaddingMode.Zeros;
_encoding = new UTF8Encoding();
}
private MemoryStream EncryptingString(string plainText, out long encryptSize)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = _cryptoAlgo.CreateEncryptor();
// Create the streams used for encryption.
//using (MemoryStream msEncrypt = new MemoryStream())
MemoryStream msEncrypt = new MemoryStream();
encryptSize = ((plainText.Length + _cryptoAlgo.FeedbackSize - 1) / _cryptoAlgo.FeedbackSize) * _cryptoAlgo.FeedbackSize;
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt, _encoding))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
}
// Return the encrypted memory stream.
return msEncrypt;
}
编辑:我尝试直接使用加密器,而不是使用流,但我遇到了同样的问题。
private MemoryStream EncryptingString(string plainText, out long encryptSize)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
ICryptoTransform encryptor = _cryptoAlgo.CreateEncryptor();
byte[] cipherData = encryptor.TransformFinalBlock(
_encoding.GetBytes(plainText), 0, plainText.Length);
// Return the encrypted memory stream.
return msEncrypt;
}