【问题标题】:How to Encrypt and Decrypt multiple text and image files within folders如何加密和解密文件夹中的多个文本和图像文件
【发布时间】:2016-11-22 15:19:32
【问题描述】:

使用以下代码对单个 .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”)将被新输出替换。

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

【问题讨论】:

    标签: vb.net loops encryption basic


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-20
      • 1970-01-01
      • 2012-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多