Leo*_*Hat 4 .net c# encryption cryptography aes
我试图用来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;
}
// ...
Run Code Online (Sandbox Code Playgroud)
这可以加密文件.现在我试图在Windows上使用Linux支持的第三方实用程序解密文件,让我相信Linux开发人员能够解密它.
快速搜索SourceForge让我进入Enqrypt.但是,如果我Enqrypt在加密文件上使用如下:
enqrypt.exe -d -aes -256 -cbc -k ABCDABCDABCDABCDABCDABCDABCDABCD myFile.encrypted.txt
Run Code Online (Sandbox Code Playgroud)
其中-d表示解密,-256表示密钥大小,-cbc模式和-k密钥前面.
它没有给我原始文件.
我尝试了一些第三方实用程序,但我似乎无法解密它.
我试图加密和解密这个文件有什么明显的错误吗?
根据@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 };
Run Code Online (Sandbox Code Playgroud)
块大小仍为128,代码中的密钥大小仍为256.
我现在尝试使用openssl如下解密文件:
openssl enc -d -aes-256-cbc -in c:\encrypted.txt -out c:\decrypted.txt -K 11223344556677881122334455667788 -iv 11223344556677881122334455667788
Run Code Online (Sandbox Code Playgroud)
这会导致以下错误:
bad decrypt 11452:error:06065064:digital envelope routines:EVP_DecryptFinal:bad decrypt:evp_enc.c:450:
Run Code Online (Sandbox Code Playgroud)
知道我做错了什么吗?
我在解密时找到了解决问题的方法openssl(在问题的更新部分).
首先,我的密钥长度是错误的(正如@PaŭloEbermann所建议的那样) - 应该是256位.
但最后一个问题是我在密钥后设置密钥大小:
AesManaged aes = new AesManaged();
aes.Key = key;
aes.IV = IV;
aes.BlockSize = 128;
aes.KeySize = 256;
aes.Mode = CipherMode.CBC;
Run Code Online (Sandbox Code Playgroud)
如果我将上面的代码更改为以下代码,我可以使用以下代码解密它openssl:
AesManaged aes = new AesManaged();
aes.BlockSize = 128;
aes.KeySize = 256;
aes.Key = key;
aes.IV = IV;
aes.Mode = CipherMode.CBC;
Run Code Online (Sandbox Code Playgroud)
感谢这个回答让我朝着正确的方向前进,并感谢其他人的回答!
| 归档时间: |
|
| 查看次数: |
7250 次 |
| 最近记录: |