如何加密和解密文件夹中的多个文本和图像文件

时间:2016-11-22 15:19:32

标签: vb.net loops encryption basic

使用以下代码加密和解密单个.txt文件:

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles SelectFile.Click

    'Create a File Dialog Box to select the source file
    Dim dlg As New OpenFileDialog
    'If OK Button is Click then add file name with path to textBox1
    If dlg.ShowDialog() = DialogResult.OK Then
        TextBox1.Text = dlg.FileName
    End If
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Encrypt.Click
    Dim outputFile As String
    outputFile = "M:\Encryptions\Encrypted.txt"
    Dim fsInput As New FileStream(TextBox1.Text, FileMode.Open, FileAccess.Read)
    Dim fsEncrypted As New FileStream(outputFile, FileMode.Create, FileAccess.Write)
    Dim sKey As String
    sKey = "Helloabc"

    Dim DES As New DESCryptoServiceProvider
    DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey)
    DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey)
    Dim desencrypt As ICryptoTransform
    desencrypt = DES.CreateEncryptor()

    Dim cryptostream As New CryptoStream(fsEncrypted, desencrypt, CryptoStreamMode.Write)
    Dim bytearrayinput(fsInput.Length) As Byte
    fsInput.Read(bytearrayinput, 0, bytearrayinput.Length)
    cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length)
    cryptostream.Close()
    fsInput.Close()
    fsEncrypted.Close()
    TextBox2.Text = "M:\Encryptions\Encrypted.txt"
End Sub
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Decrypt.Click
    Dim DES As New DESCryptoServiceProvider
    Dim sKey As String
    sKey = "Helloabc"
    DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey)
    DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey)
    Dim fsread As New FileStream(TextBox2.Text, FileMode.Open, FileAccess.Read)
    Dim desdecrypt As ICryptoTransform
    desdecrypt = DES.CreateDecryptor()

    Dim cryptostreamDecr As New CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read)
    Dim fsDecrypted As New StreamWriter("M:\Decryptions\Decrypted.txt")
    fsDecrypted.Write(New StreamReader(cryptostreamDecr).ReadToEnd())
    fsDecrypted.Flush()
    fsDecrypted.Close()
    TextBox3.Text = "M:\Decryptions\Decrypted.txt"
End Sub

但是,在尝试加密/解密多个文件时,原始输出加密/解密文件(“Encrypted.txt”)将被新输出替换。

如何创建循环以创建具有不同文件名的多个加密文件?

1 个答案:

答案 0 :(得分:0)

使用计数器:0,1,2,3,4 ...将计数器附加到文件名并在每个文件写入后逐步执行计数器:

Encrypted00.dat
Encrypted01.dat
Encrypted02.dat
Encrypted03.dat
...

调用加密文件.txt可能是错误的,因为它们不是文本。它们是二进制数据。如果您希望它们作为文本,那么您将需要转换为Base64格式,并在解密之前转换回二进制数据。

或者,将目录中的所有文件压缩到一个文件中并加密该单个文件。