我有一个现有的 zip 文件,我想使用 AESManaged 类对其进行加密,但我找不到可以在该类中为 zip 文件设置密码的位置。经过研究,我发现一些库如“DotNetZip”可以完成这个任务。但是我的文件已经是.zip了,我不用再压缩了,我只想加密一下。任何人都可以帮助我使用 AESManaged 类来实现目的吗?
谢谢
最佳答案
我不知道这是否是您正在寻找的,但我创建了一个加密任何文件的代码。
这是加密器的代码:
private void EncryptFile(string inputFile, string outputFile)
{
string password = @"yourPWhere";
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = CreateKey(password);
string cryptFile = outputFile;
FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);
RijndaelManaged RMCrypto = new RijndaelManaged();
IV = CreateIV(password_mTxtBx.Text);
CryptoStream cs = new CryptoStream(fsCrypt,
RMCrypto.CreateEncryptor(key,IV),
CryptoStreamMode.Write);
FileStream fsIn = new FileStream(inputFile, FileMode.Open);
int data;
while ((data = fsIn.ReadByte()) != -1)
cs.WriteByte((byte)data);
fsIn.Close();
cs.Close();
fsCrypt.Close();
}
这是解密器的代码:
private void DecryptFile(string inputFile, string outputFile)
{
string password = @"yourPWhere";
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = CreateKey(password);
FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);
RijndaelManaged RMCrypto = new RijndaelManaged();
IV = CreateIV(password_mTxtBx.Text);
CryptoStream cs = new CryptoStream(fsCrypt,
RMCrypto.CreateDecryptor(key, IV),
CryptoStreamMode.Read);
FileStream fsOut = new FileStream(outputFile.Remove(outputFile.Length - 4), FileMode.Create);
int data;
while ((data = cs.ReadByte()) != -1)
fsOut.WriteByte((byte)data);
fsOut.Close();
cs.Close();
fsCrypt.Close();
}
我几个月前在codeproject上看到过类似的代码。所以这不是我的直接工作。 学分归作者所有。
更新了基于密码的 key 派生 (PBKDF2):
private static int saltLengthLimit = 32;
private static byte[] GetSalt(int maximumSaltLength)
{
var salt = new byte[maximumSaltLength];
using (var random = new RNGCryptoServiceProvider())
{
random.GetNonZeroBytes(salt);
}
return salt;
}
public static byte[] CreateKey(string password)
{
var salt = GetSalt(10);
int iterationCount = 20000; // Nowadays you should use at least 10.000 iterations
using (var rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, salt, iterationCount))
return rfc2898DeriveBytes.GetBytes(16);
}
IV 的创建者(从密码创建):
public byte[] CreateIV(string password)
{
var salt = GetSalt(9);
const int Iterations = 325;
using (var rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, salt, Iterations))
return rfc2898DeriveBytes.GetBytes(16);
}
key 的字节长度在我的例子中是 128 位 (!) = 16 字节 (128/8),但您可以使用 Rijndael 支持的任何其他长度( key :128、192、256 位 = 16、24、 32 字节)。 IV 始终为 16 个字节!
关于c# - 加密现有的 zip 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12795017/