Imports
Imports .IO
Imports .Security
Imports .Security.Cryptography
Imports .Text
Module Encrypt
Private Const sSecretKey As String = \"password\"
Public Sub Main
EncryptFile(\"c:\\temp\\test.txt\", _
\"c:\\temp\\Encrypted.txt\", _
sSecretKey)
DecryptFile(\"c:\\temp\\Encrypted.txt\", _
\"c:\\temp\\Decrypted.txt\", _
sSecretKey)
End Sub
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算法设置安全码.
\'必须是64位,8个字节
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey)
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey)
\'创建DES加密码例子
Dim desencrypt As ICryptoTransform = DES.CreateEncryptor
\'
Dim cryptostream As New CryptoStream(fsEncrypted, _
desencrypt, _
CryptoStreamMode.Write)
\'读取文件到
Dim .gif' />input(fsInput.Length - 1) As Byte
fsInput.Read(.gif' />input, 0, .gif' />input.Length)
\'写到加密文件中
cryptostream.Write(.gif' />input, 0, .gif' />input.Length)
cryptostream.Close
End Sub
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
End Module
最新评论