标题用VB实现文件加密
栏目软件世界
作者郭辉
发布2001年46期
大家知道,电报有“明码”电报和“密码”电报之分,而后者就是用另一套符号来代替原文内容,从而起到加密的作用。这种方法即使是专业人士,破解起来也要颇费些功夫。在计算机上,每一个字符都有其对应的ASCII代码,我们可以通过更改这个代码的办法来实现“密码文件”。
启动VB,新建一个标准EXE工程。在窗体上添加四个CommandButton控件,其Caption属性分别为“打开文件”、“加密文件”、“解密文件”和“保存文件”;再添加一个RichTextBox控件和一个Commondialog控件(一般的Textbox控件也可以,但它对文本大小有限制,无法处理较大的文件),双击窗体,添加以下代码:
Private Sub Command1_Click() '打开文件
CommonDialog1.Filter = “Text File(*.txt)|*.txt|All File (*.*)|*.*”
CommonDialog1.ShowOpen
RTB1.LoadFile CommonDialog1.FileName
End Sub
Private Sub Command2_Click() '加密文件
Dim s, temp,t As String
Dim i As Single
s = RTB1.Text
t = “”
For i = 1 To Len(s)
temp = Mid$(s, i,1)
temp = Chr(Asc(temp) - 1) '转换Ascii代码
t = t + temp
Next i
RTB1.Text = t
End Sub
Private Sub Command3_Click() '解密文件
Dim s,temp, t As String
Dim i As Single
s = RTB1.Text
t = “”
For i = 1 To Len(s)
temp = Mid$(s, i, 1)
temp = Chr(Asc(temp) + 1)
t = t + temp
Next i
RTB1.Text = t
End Sub
Private Sub Command4_Click() '保存文件
CommonDialog1.Filter = “Text File(*.txt)|*.txt|All File(*.*)|*.*”
CommonDialog1.ShowSave
Open CommonDialog1.FileName For Output As #1
Print #1,RTB1.Text
Close #1
End Sub
在程序中,加密的方法是把每一个字符的ASCII代码都减去1,解密时则相反。事实上,如果把“加密文件”按钮和“解密文件”按钮互换,也可以完成任务。但此时解密后的文件会出现个别乱码。有兴趣的朋友可以研究一下,把这个程序做得更完美!