新客网WWW.XKER.COM:致力做中国最专业的网络学院!
学院: 操作系统 - 网络应用 - 服务器 - 网络安全 - 工具软件 - 办公软件 - Web开发 - 数据库 - 网页设计 - 图形图像 - 媒体动画 - 硬件学堂 - 存储频道 - QQ专区
您的位置:首页 > 软件开发 > .Net开发 > Asp.net教程 > 正文:使用vb.net加密和解密文件。(好象英文灵,中文不灵)

使用vb.net加密和解密文件。(好象英文灵,中文不灵)

新客网 XKER.COM 2003-07-12 来源: 收藏本文
Imports System
Imports System.IO
Imports System.Security
Imports System.Security.Cryptography
Imports System.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 bytearrayinput(fsInput.Length - 1) As Byte
        fsInput.Read(bytearrayinput, 0, bytearrayinput.Length)
        '写到加密文件中
        cryptostream.Write(bytearrayinput, 0, bytearrayinput.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
收藏】 【评论】 【推荐】 【投稿】 【打印】 【关闭
发表评论
要记得去论坛讨论,点击注册新会员匿名评论
评论内容:不能超过250字,需审核后才会公布,请自觉遵守互联网相关政策法规。
阅读排行
随机推荐
实用信息推荐