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