我在下面的代码中遇到了一些问题。我在一个临时位置有一个需要加密的文件,此函数加密该数据,然后将其存储在"pathToSave“位置。
在检查时,is似乎没有正确处理整个文件-我的输出中缺少一些位,我怀疑这与while循环没有在整个流中运行有关。
另外,如果我尝试在while循环之后调用CryptStrm.Close(),我会收到一个异常。这意味着,如果我试图解密文件,我会得到一个文件已在使用错误!
尝试了所有常见的方法,我在这里看到了类似的问题,任何帮助都会很好。
谢谢
public void EncryptFile(String tempPath, String pathToSave)
{
try
{
FileStream InputFile = new FileStream(tempPath, FileMode.Open, FileAccess.Read);
FileStream OutputFile = new FileStream(pathToSave, FileMode.Create, FileAccess.Write);
RijndaelManaged RijCrypto = new RijndaelManaged();
//Key
byte[] Key = new byte[32] { ... };
//Initialisation Vector
byte[] IV = new byte[32] { ... };
RijCrypto.Padding = PaddingMode.None;
RijCrypto.KeySize = 256;
RijCrypto.BlockSize = 256;
RijCrypto.Key = Key;
RijCrypto.IV = IV;
ICryptoTransform Encryptor = RijCrypto.CreateEncryptor(Key, IV);
CryptoStream CryptStrm = new CryptoStream(OutputFile, Encryptor, CryptoStreamMode.Write);
int data;
while (-1 != (data = InputFile.ReadByte()))
{
CryptStrm.WriteByte((byte)data);
}
}
catch (Exception EncEx)
{
throw new Exception("Encoding Error: " + EncEx.Message);
}
}编辑:
我假设我的问题与加密有关。我的解密可能就是罪魁祸首
public String DecryptFile(String encryptedFilePath)
{
FileStream InputFile = new FileStream(encryptedFilePath, FileMode.Open, FileAccess.Read);
RijndaelManaged RijCrypto = new RijndaelManaged();
//Key
byte[] Key = new byte[32] { ... };
//Initialisation Vector
byte[] IV = new byte[32] { ... };
RijCrypto.Padding = PaddingMode.None;
RijCrypto.KeySize = 256;
RijCrypto.BlockSize = 256;
RijCrypto.Key = Key;
RijCrypto.IV = IV;
ICryptoTransform Decryptor = RijCrypto.CreateDecryptor(Key, IV);
CryptoStream CryptStrm = new CryptoStream(InputFile, Decryptor, CryptoStreamMode.Read);
String OutputFilePath = Path.GetTempPath() + "myfile.name";
StreamWriter OutputFile = new StreamWriter(OutputFilePath);
OutputFile.Write(new StreamReader(CryptStrm).ReadToEnd());
CryptStrm.Close();
OutputFile.Close();
return OutputFilePath;
}发布于 2020-02-05 19:58:17
另一种读取CryptoStream的方法是使用CopyTo方法:
...
using (var output = new MemoryStream())
{
cryptStream.CopyTo(output);
return output.ToArray();
}
...发布于 2019-01-18 04:08:57
必须先指定KeySize。这看起来像是个bug
using (var aes = new AesManaged())
{
aes.KeySize = 256;
aes.Mode = CipherMode.CBC;
aes.IV = iv;
aes.Key = passwordHash;
aes.Padding = PaddingMode.PKCS7;但这不是
using (var aes = new AesManaged())
{
aes.Mode = CipherMode.CBC;
aes.IV = iv;
aes.Key = passwordHash;
aes.Padding = PaddingMode.PKCS7;
aes.KeySize = 256;https://stackoverflow.com/questions/9724598
复制相似问题