你好我一直都試圖用System.Security.Cryptography加密和解密文件,但它不是爲我工作VB.net中的加密 - 解密文件大於源文件?
這個代碼
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不合適,讀取原始文件時沒有使用它。 –