用VB进行文件加密
?牐牸用茉恚貉肥褂妹苈胫忻扛鲎址腁SCII码值与文件的每个字节进行异或运算,然后写入文件即可。这种加密方法是可逆的,即对明文进行加密得到密文,用相同的密码对密文进行加密就得到明文。
?牐牻缑嫔杓疲涸诖疤錐rom1上放置驱动器列表框(Driver1)、目录列表框(Dir1)、文件列表框(File1)各一个,这三个控件相互配合,用来确定要加密文件的位置。其中File1的Pattern属性设为“*.TXT”,即仅显示文本文件;再放置一个Check控件,用来控制显示文件的类型,其Caption属性设为“显示全部文件”;接着放置两个文本框,Text1显示文件内容,Text2用来输入密码,其Passchar属性设为“*”,一个Label控件,其Caption属性设为“密码”;最后,放置两个命令按钮,其Caption属性分别设为“加密/解密”和“退出”。
?牐牫绦虼耄?
?牐燨ption Explicit
?牐燚im i As Long
?牐燚im databuff() As Byte '定义数组用于存放文件内容
?牐燚im addbuff() As Byte '定义数组用于存放加密后的文件内容
?牐燚im password() As Byte '定义数组用于存放密码的ASCII值
?牐燚im filename As String
?牐燩rivate Sub Check1_Click()?煟?
?牐營f Check1.Value Then '控制是否显示全部文件
?牐燜ile1.Pattern = "*.*"
?牐燛lse
?牐燜ile1.Pattern = ".txt"
?牐燛nd If
?牐燛nd Sub
?牐燩rivate Sub Command1_Click()?煟?
?牐燚im j As Integer
?牐燚im password_len As Integer
?牐爌assword_len = Len(Text2.Text)??
?牐燫eDim password(password_len) As Byte
?牐燜or i = 0 To password_len - 1 '把密码转化为ASCII码
?牐爌assword(i)= Asc(Mid(Text2.Text,i + 1,1))?牐?
?牐燦ext
?牐營f filename = "" Then Exit Sub
?牐燨pen filename For Binary As #1 '读取要加密的文件内容
?牐燫eDim databuff(LOF(1))?牐?
?牐燝et #1,, databuff
?牐燙lose #1
?牐燫eDim addbuff(UBound(databuff))As Byte
?牐燜or i = 0 To UBound(databuff)??
?牐營f j >= password_len Then '循环使用密码
?牐爅 = 0
?牐燛lse
?牐爅 = j + 1
?牐燛nd If
?牐燼ddbuff(i)= databuff(i)Xor password(j)'进行异或运算
?牐燦ext
?牐燨pen filename For Binary As #1 '把加密后的内容写入文件
?牐燩ut #1,,addbuff
?牐燙lose #1
?牐燭ext1 = StrConv(addbuff vbUnicode)'显示加密后的文件内容
?牐燭ext2.Text = ""
?牐燛nd Sub
?牐燩rivate Sub Command2_Click()?煟?
?牐?.End
?牐燛nd Sub
?牐燩rivate Sub Dir1_Change()?煟?
?牐燜ile1.Path = Dir1.Path '与文件列表框相关联
?牐燛nd Sub
?牐燩rivate Sub Drive1_Change()?煟?
?牐燨n Error GoTo a0
?牐燚ir1.Path = Drive1.Drive '与目录列表框相关联
?牐燼0:If Err Then MsgBox(Error(Err))'发生错误,提示错误内容
?牐燛nd Sub
?牐燩rivate Sub File1_Click()'单击文件时,显示文件内容
?牐爁ilename = Dir1.Path + File1.filename
?牐營f filename = "" Then Exit Sub
?牐燨pen filename For Binary As #1
?牐燫eDim databuff(LOF(1))?牐?
?牐燝et #1,,databuff
?牐燙lose #1
?牐燭ext1 = StrConv(databuff,vbUnicode)??
?牐燛nd Sub