【发布时间】:2012-06-15 16:49:55
【问题描述】:
您好,我一直在尝试使用 System.Security.Cryptography 来加密和解密文件,但它对我不起作用
这段代码
Private Sub EncryptFile(ByVal sInputFilename As String, ByVal sOutputFilename As String, ByVal sKey As String)
Dim fsInput As New FileStream(sInputFilename, FileMode.Open, FileAccess.Read)
Dim fsEncrypted As New FileStream(sOutputFilename, FileMode.Create, FileAccess.Write)
Dim DES As New DESCryptoServiceProvider()
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey)
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey)
Dim desencrypt As ICryptoTransform = DES.CreateEncryptor()
Dim cryptostream As New CryptoStream(fsEncrypted, desencrypt, CryptoStreamMode.Write)
Dim bytearrayinput(fsInput.Length - 1) As Byte
fsInput.Read(bytearrayinput, 0, bytearrayinput.Length)
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length)
cryptostream.Close()
End Sub
调用
EncryptFile(OpenFileDialog1.FileName, SaveFileDialog1.FileName, "12345678")[/CODE]
似乎工作正常,我得到一个与源文件大小相同的文件
这里出了问题
这段代码
Private Sub DecryptFile(ByVal sInputFilename As String, ByVal sOutputFilename As String, ByVal sKey As String)
Dim DES As New DESCryptoServiceProvider()
DES.Key() = ASCIIEncoding.ASCII.GetBytes(sKey)
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey)
Dim fsread As New FileStream(sInputFilename, FileMode.Open, FileAccess.Read)
Dim desdecrypt As ICryptoTransform = DES.CreateDecryptor()
Dim cryptostreamDecr As New CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read)
Dim fsDecrypted As New StreamWriter(sOutputFilename)
fsDecrypted.Write(New StreamReader(cryptostreamDecr).ReadToEnd)
fsDecrypted.Flush()
fsDecrypted.Close()
End Sub
调用
DecryptFile(OpenFileDialog1.FileName, SaveFileDialog1.FileName, "12345678")[/CODE]
输出的文件几乎是加密源文件的 2 倍。
我确定这在几周前运行良好,我看不出有什么明显的问题。
有什么想法吗?
【问题讨论】:
-
使用StreamReader/Writer不合适,读取原文件时没有使用。
标签: vb.net encryption cryptography