【发布时间】:2011-11-11 05:34:32
【问题描述】:
我正在尝试使用System.Security.Cryptography.AesManaged 来加密我的 .net 应用程序中的文件。它需要在嵌入式 Linux 环境中解密,因此我无法使用 .net 库。
我现在的代码看起来像这样:
string encPassword = "ABCDABCDABCDABCDABCDABCDABCDABCD";
string sourceFile = "myFile.txt";
string targetFile = "myFile.encrypted.txt";
FileStream fsInput = = new FileStream(sourceFile, FileMode.Open, FileAccess.Read);
FileStream fsOutput = new FileStream(targetFile, FileMode.OpenOrCreate, FileAccess.Write);
CryptoStream cryptoStream = null;
try
{
byte[] key = Encoding.ASCII.GetBytes(encPasswd);
byte[] IV = new byte[16];
Array.Copy(key, 0, IV, 0, 16);
AesManaged aes = new AesManaged();
aes.Key = key;
aes.IV = IV;
aes.BlockSize = 128;
aes.KeySize = 256;
aes.Mode = CipherMode.CBC;
ICryptoTransform encryptor = aes.CreateEncryptor();
cryptoStream = new CryptoStream(fsOutput, encryptor, CryptoStreamMode.Write);
byte[] buffer = new byte[BUFFER_LENGTH];
long bytesProcessed = 0;
long fileLength = fsInput.Length;
int bytesInCurrentBlock;
do
{
bytesInCurrentBlock = fsInput.Read(buffer, 0, BUFFER_LENGTH);
cryptoStream.Write(buffer, 0, bytesInCurrentBlock);
bytesProcessed = bytesProcessed + bytesInCurrentBlock;
}
while (bytesProcessed < fileLength);
return true;
}
// ...
这可以加密文件。现在我正在尝试在 Windows 上使用 Linux 也支持的第 3 方实用程序来解密该文件,以使我相信 Linux 开发人员能够解密它。
在 SourceForge 上快速搜索让我到 Enqrypt。但是,如果我像这样在加密文件上使用Enqrypt:
enqrypt.exe -d -aes -256 -cbc -k ABCDABCDABCDABCDABCDABCDABCDABCD myFile.encrypted.txt
其中-d 表示解密,-256 表示密钥大小,-cbc 表示模式,-k 在密钥前面。
它没有给我原始文件。
我已经尝试过使用一些 3rd 方实用程序,但我似乎无法解密它。
我尝试加密和解密此文件的方式是否存在明显错误?
更新
响应@Paŭlo 的建议,我现在有以下测试代码(别担心,我打算将密钥和IV 更改为不同):
byte[] key = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 };
byte[] IV = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 };
代码中块大小仍然是128,密钥大小仍然是256。
我现在尝试使用openssl 解密文件,如下所示:
openssl enc -d -aes-256-cbc -in c:\encrypted.txt -out c:\decrypted.txt -K 11223344556677881122334455667788 -iv 11223344556677881122334455667788
这会导致以下错误:
bad decrypt 11452:error:06065064:digital envelope routines:EVP_DecryptFinal:bad decrypt:evp_enc.c:450:
知道我做错了什么吗?
【问题讨论】:
-
您的最后一条错误消息看起来像 OpenSSL 需要一些填充方案,但它不存在(但这也可能是由错误的键/IV 组合引起的)。此外,您只传递一个 16 字节的密钥,而 AES-256 需要一个 32 字节的密钥。 (当您传递太短的密钥时,我不知道 OpenSSL 和 .NET 在做什么,但我可以想象它们不会做同样的事情。)
-
@Paŭlo - 我将 key 更改为 32 字节数组,但没有任何区别。填充方案适用于什么,
key、IV或两者都适用?IV的长度应该和key一样吗? -
CBC 的 IV 长度应与块大小(AES 为 128 位/16 字节)相同,与密钥大小无关。在加密之前将填充方案应用于纯文本,以确保纯文本的大小是块大小的倍数。虽然documentation 表示默认值为 PKCS7,这与 openssl 工具使用的相同。我在这里没有想法......
-
@Paŭlo - 感谢您的所有帮助。我终于找到了解决方案 - 请参阅my answer。
标签: c# .net encryption cryptography aes