我正在使用Rijndael
算法加密pdf文件。加密和解密工作正常。加密会将pdf文件转换为扩展名为.key
的文件。如何在解密之前保护加密文件不被破坏
问题是我可以在notepad
(它显示一些Unicode字符)打开此文件并损坏它。考虑到这种情况下:
我已经打开了文件,并删除一些字符/添加一些文字和save the notepad file
。如果我将这个文件传递给解密方法,我会将损坏的文件作为输出。我知道这是因为在添加或删除文件中的字符时byteStream变化(填充已更改)。
这里是我的问题:
有什么办法来解决这个问题?换句话说,禁止编辑加密文件?**
以下是方法我用了加密,
VB代码
Dim plainFile As String = basePath & "\cryptoText.pdf"
Dim password As String = "somePass"
Dim UE As New UnicodeEncoding()
Dim key As Byte() = UE.GetBytes(password)
Dim cryptFile As String = basePath & "\cryptoText.key"
Dim fsCrypt As New FileStream(cryptFile, FileMode.Create)
Dim RMCrypto As New RijndaelManaged()
Using csKey As New CryptoStream(fsCrypt, RMCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write)
Dim FsIn As New FileStream(plainFile, FileMode.Open)
Dim data As Integer
While (data = FsIn.ReadByte()) <> -1
csKey.WriteByte(CByte(data))
End While
FsIn.Close()
End Using
fsCrypt.Close()
C#代码
string plainFile = basePath + "\\cryptoText.pdf";
string password = "somePass";
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(password);
string cryptFile = basePath + "\\cryptoText.key";
FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);
RijndaelManaged RMCrypto = new RijndaelManaged();
using (CryptoStream csKey = new CryptoStream(fsCrypt, RMCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write)) {
FileStream FsIn = new FileStream(plainFile, FileMode.Open);
int data = 0;
while ((data == FsIn.ReadByte()) != -1) {
csKey.WriteByte(Convert.ToByte(data));
}
FsIn.Close();
}
fsCrypt.Close();
备注:我已经试过了在c#和vb.net中,以便将我的问题标记为两者。
感谢您的建议和信息链接 –
请注意,这*不*保护文件免受损坏,它只是检测损坏的文件,所以你可以采取行动。这基本上是“防篡改”与“防篡改”之间的区别。 “防篡改”的方式是禁止对文件进行写入访问。 –
请注意,上述方案尚未受到重播攻击的保护(此评论和上述评论不会使答案无效,他们只是添加安全相关信息)。 –