在加密方法中有一种最原始的替换法,即将某一字符串中的某一些字符用特定字符替换或相互交换位置,本文的例子用异或、替换的方法替换文件二进制码达到加密目的。
引用:
在
C:/ 下新建一个名为
file.txt 的文本文件,其内容为“
I love WYC!”。经加密后的新文件
file_enc.txt 文件内容为 “
Q8twn}8OA[9” 达到加密目的。
Option Explicit
Public Const GENKEY = &H18 '//密钥
Public Const GENKEY = &H18 '//密钥
Public Function CodeFile(ByVal lpSrcFile As String, _
ByVal lpDesFile As String) As Boolean
CodeFile = False
On Error GoTo ErrHandle:
If Dir(lpSrcFile) <> "" Then
Dim FileSize As Long, FileNumber As Integer
FileSize = FileLen(lpSrcFile)
Dim arrbytes() As Byte, j As Long
ReDim arrbytes(1 To FileSize) As Byte
FileNumber = FreeFile
'//打开源文件
Open lpSrcFile For Binary Access Read As #FileNumber
Get #FileNumber, , arrbytes()
Close #FileNumber
'//对每一字节进行异或处理
For j = 1 To FileSize
arrbytes(j) = Abs(arrbytes(j) Xor GENKEY)
Next j
'//写入目标文件
Open lpDesFile For Binary Access Write As #FileNumber
Put #FileNumber, , arrbytes()
Close #FileNumber
CodeFile = True
End If
ErrHandle:
End Function
ByVal lpDesFile As String) As Boolean
CodeFile = False
On Error GoTo ErrHandle:
If Dir(lpSrcFile) <> "" Then
Dim FileSize As Long, FileNumber As Integer
FileSize = FileLen(lpSrcFile)
Dim arrbytes() As Byte, j As Long
ReDim arrbytes(1 To FileSize) As Byte
FileNumber = FreeFile
'//打开源文件
Open lpSrcFile For Binary Access Read As #FileNumber
Get #FileNumber, , arrbytes()
Close #FileNumber
'//对每一字节进行异或处理
For j = 1 To FileSize
arrbytes(j) = Abs(arrbytes(j) Xor GENKEY)
Next j
'//写入目标文件
Open lpDesFile For Binary Access Write As #FileNumber
Put #FileNumber, , arrbytes()
Close #FileNumber
CodeFile = True
End If
ErrHandle:
End Function
Sub Main()
If CodeFile("c:/file.txt", "c:/file_enc.txt") = True Then
MsgBox "加密成功", vbInformation, "成功"
Else
MsgBox "加密失败", vbExclamation, "失败"
End If
End Sub
If CodeFile("c:/file.txt", "c:/file_enc.txt") = True Then
MsgBox "加密成功", vbInformation, "成功"
Else
MsgBox "加密失败", vbExclamation, "失败"
End If
End Sub