任何人都可以猜出哪个部分是错的? 我编程的代码如下。
当我读取加密文件时,我完全看不懂。 而CryptoStream的属性称为长度和位置有“NotSupportedException”, 当我使用vss看到cryptstream的属性时。
我浪费了很多时间来解决这个问题..... 请帮帮我......
加密 [位图>>加密的fie]
解密 [加密的fie>>文件]
public static void EncryptFile(
Bitmap bmp, string destFile, byte[] key, byte[] iv)
{
System.Security.Cryptography.RijndaelManaged rijndael =
new System.Security.Cryptography.RijndaelManaged();
rijndael.Key = key;
rijndael.IV = iv;
System.IO.FileStream outFs = new System.IO.FileStream(
destFile, System.IO.FileMode.Create, System.IO.FileAccess.Write);
System.Security.Cryptography.ICryptoTransform encryptor =
rijndael.CreateEncryptor();
System.Security.Cryptography.CryptoStream cryptStrm =
new System.Security.Cryptography.CryptoStream(
outFs, encryptor,
System.Security.Cryptography.CryptoStreamMode.Write);
MemoryStream ms = new MemoryStream();
bmp.Save(ms, ImageFormat.Jpeg);
byte[] bs = new byte[1024];
int readLen;
while ((readLen = ms.Read(bs, 0, bs.Length)) > 0)
{
cryptStrm.Write(bs, 0, readLen);
}
ms.Close();
cryptStrm.Close();
encryptor.Dispose();
outFs.Close();
}
public static void DecryptFile(
string sourceFile, string destFile, byte[] key, byte[] iv)
{
System.Security.Cryptography.RijndaelManaged rijndael =
new System.Security.Cryptography.RijndaelManaged();
rijndael.Key = key;
rijndael.IV = iv;
System.IO.FileStream inFs = new System.IO.FileStream(
sourceFile, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.Security.Cryptography.ICryptoTransform decryptor =
rijndael.CreateDecryptor();
System.Security.Cryptography.CryptoStream cryptStrm =
new System.Security.Cryptography.CryptoStream(
inFs, decryptor,
System.Security.Cryptography.CryptoStreamMode.Read);
System.IO.FileStream outFs = new System.IO.FileStream(
destFile, System.IO.FileMode.Create, System.IO.FileAccess.Write);
byte[] bs = new byte[1024];
int readLen;
while ((readLen = cryptStrm.Read(bs, 0, bs.Length)) > 0)
{
outFs.Write(bs, 0, readLen);
}
outFs.Close();
cryptStrm.Close();
decryptor.Dispose();
inFs.Close();
}
答案 0 :(得分:0)
尝试设置rijndael的Mode和Padding成员
当我执行类似的实现时,默认填充模式会导致问题。
// It is reasonable to set encryption mode to Cipher Block Chaining
// (CBC). Use default options for other symmetric key parameters.
rijndael.Mode = CipherMode.CBC;
rijndael.Padding = PaddingMode.None;