Base64编码的思想是是采用64个基本的ASCII码字符对数据进行重新编码,将数据变成字符串实现文本传输。由于编码简单,所以很容易实现,代码也是现成的。利用这个编码规则可以实现简单的加解密。编解码方法见: VB实现Base64 编解码
我用VBA做了个简单的系统,其中用到用户登录,自然要保存用户名和密码。密码存放在数据库中,不想明码保存,于是就想到用这个编码方法进行加密。Base64编码是按照64个字符字典进行编码的,为了加密,这64个字符可以打乱原来的顺序,也可以用其他字符替换掉部分字符,如果不考虑解码,这个字符字典中的字符甚至可以重复。比如密码保存,只需比较密文,不需要还原成明文进行比较,那么字符字典中重复也是没有问题的,可以任意取64个字符作为字典。
下面这个函数就可以用来生成密码的密文,其中的数据字典是用个随机函数随意生成的:
Function B64Encode(sou_str As String) As String 'Base64 编码
On Error GoTo over '排错
Dim buf() As Byte, length As Long, mods As Long
Dim Str() As Byte, kk As Long, i As Long
'字符字典(用随机产生的)
Const B64_CHAR_DICT = "Qx7mCcL2XsYm!Q^ZjKeLn#r2H4rV6B(Xu$v$zU2@CnHfVf7tH9XrBcB9WyA6F%Ah."
kk = Len(sou_str) - 1
ReDim Str(kk)
For i = 0 To kk
Str(i) = Asc(Mid(sou_str, i + 1, 1))
Next i
mods = (UBound(Str) + 1) Mod 3 '除以3的余数
length = UBound(Str) + 1 - mods
ReDim buf(length / 3 * 4 + IIf(mods <> 0, 4, 0) - 1)
For i = 0 To length - 1 Step 3
buf(i / 3 * 4) = (Str(i) And &HFC) / &H4
buf(i / 3 * 4 + 1) = (Str(i) And &H3) * &H10 + (Str(i + 1) And &HF0) / &H10
buf(i / 3 * 4 + 2) = (Str(i + 1) And &HF) * &H4 + (Str(i + 2) And &HC0) / &H40
buf(i / 3 * 4 + 3) = Str(i + 2) And &H3F
Next
If mods = 1 Then
buf(length / 3 * 4) = (Str(length) And &HFC) / &H4
buf(length / 3 * 4 + 1) = (Str(length) And &H3) * &H10
buf(length / 3 * 4 + 2) = 64
buf(length / 3 * 4 + 3) = 64
ElseIf mods = 2 Then
buf(length / 3 * 4) = (Str(length) And &HFC) / &H4
buf(length / 3 * 4 + 1) = (Str(length) And &H3) * &H10 + (Str(length + 1) And &HF0) / &H10
buf(length / 3 * 4 + 2) = (Str(length + 1) And &HF) * &H4
buf(length / 3 * 4 + 3) = 64
End If
For i = 0 To UBound(buf)
B64Encode = B64Encode + Mid(B64_CHAR_DICT, buf(i) + 1, 1)
Next
over:
End Function
'调用测试
Private Sub ttt()
aa = B64Encode("iamlaosong")
bb = B64Encode("iamlaosong")
MsgBox aa & " " & bb
End Sub
关于随机字符串的产生,见:【VBA研究】生成随机密码
---------------------