ASP.NET - 加密文件



我正在使用 ASP.NET 执行一项任务,其中用户必须上传文件,并且我使用已经完成的加密算法进行了加密。该文件的属性包括:IDNametags。现在,在我加密字符串(例如名称(之前,我从未加密过文件,对此一无所知。

我到底需要加密什么?

加密算法:

public static void HybridEncrypt(string publicKey, MemoryStream fileToEncrypt, string filenameOfTheOutputFile)
{
var publicKeyPath = Path.Combine(Directory.GetCurrentDirectory(), "\publickey.key");
Rijndael myAlg = Rijndael.Create();
myAlg.GenerateIV(); //this is another method how to generate the secret key and iv
myAlg.GenerateKey();
byte[] keyStream = myAlg.Key;
byte[] IVstream = myAlg.Key;
MemoryStream msFileDataEncrypted = SymmetricEncryptData(fileToEncrypt, keyStream, IVstream);
MemoryStream keyStreamEncrypt = new MemoryStream(myAlg.Key);
MemoryStream msEncryptedSecretKey = new Encryption().AsymmetricallyEncrypt(publicKeyPath, keyStreamEncrypt);
MemoryStream IVStreamEncrypt = new MemoryStream(myAlg.IV);
MemoryStream msEncryptedIV = new Encryption().AsymmetricallyEncrypt(publicKeyPath, IVStreamEncrypt);
MemoryStream msAll = new MemoryStream();
msEncryptedSecretKey.Position = 0;
msEncryptedIV.Position = 0;
msFileDataEncrypted.Position = 0;
msEncryptedSecretKey.CopyTo(msAll);
msEncryptedIV.CopyTo(msAll);
msFileDataEncrypted.CopyTo(msAll);
System.IO.File.WriteAllBytes(filenameOfTheOutputFile, msAll.ToArray());
}

您需要解决 3 件事

  1. 根据奥列克萨的评论,您需要从byte[] IVstream = myAlg.Key;更正为byte[] IVstream = myAlg.IV;
  2. 您应该通过从httppostedfilebase to memorystream c#转换来加密文件,然后作为参数传递fileToEncrypt而不是Encoding.UTF32.GetBytes(stringvale)
  3. ID, Name, and tags只是存储在数据库中的信息,无需对其进行加密。

最有可能的是,您的初始向量大小小于 16 字节。您需要增加初始矢量大小。

最新更新