使用.NET对文件进行DES加密

  代码摘自Lieo最近编写的程序,参考自《Visual Basic 2003~2005开发秘诀与范例大全》。

  代码中的密钥是一个8字节64位的字符串,得到该字符串即可解密文件。程序中并为对该密钥进行保护处理。(可以通过导入的DLL函数ZeroMemory在密钥使用后清除该密钥)

Imports System.IO
Imports System.Security.Cryptography
Imports System.Runtime.InteropServices
Imports System.Text

    <DllImport("kernel32.dll")> Public Sub ZeroMemory(ByVal addr As IntPtr, ByVal size As Integer)
    End Sub

    Private Sub Encrypt(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 ByteInput(CInt(fsInput.Length - 1)) As Byte
        fsInput.Read(ByteInput, 0, ByteInput.Length)
        cryptostream.Write(ByteInput, 0, ByteInput.Length)
        cryptostream.Close()
        fsInput.Close()
        fsEncrypted.Close()
    End Sub

    Private Sub Decrypt(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 cryptostreamDescr As New CryptoStream(fsRead, desdecrypt, CryptoStreamMode.Read)

        Dim fsDecrypted As New StreamWriter(sOutputFileName)
        fsDecrypted.Write(New StreamReader(cryptostreamDescr).ReadToEnd)
        fsDecrypted.Flush()
        fsDecrypted.Close()
        fsRead.Close()
    End Sub
✏️ 有任何想法?欢迎发邮件告诉老夫:daozhihun@outlook.com