最近需要用VB写个小测试程序,所以把荒废了很久很久的vb翻了出来,从网上找了个10来兆的绿色版装上了。代码中测试中需要用到RC4的算法,于是从网上搜了一圈,结果很是失望,真正能用的几乎没有,网络上四处传播的那个代码,算法上应该说还是对的,但是采用String作为函数参数,结果处理的反而成错的了。这个错误的东西还四处传播,真是天下文章一大抄啊,居然这么多转贴的就没人做个简单的测试? 于是顺手按照c的代码,简单写了个程序,采用的是Byte数组来传递参数。调用的时候,可以采用strConv将普通的String和Byte数组做转换,或者省事就直接用String也是没问题的。
Option Base 0
Public Type rc4_key
s(256) As Byte
x As Byte
y As Byte
End Type
Public Sub prepare_key(ByRef key_data() As Byte, ByRef key As rc4_key)
Dim i As Long, j As Byte, keylen As Long, c As Integer
For c = 0 To 255
key.s(c) = c
Next
key.x = 0
key.y = 0
i = 0
j = 0
keylen = UBound(key_data) - LBound(key_data) + 1
For c = 0 To 255
j = ((key_data(i) Mod 256) + key.s(c) + j) Mod 256
key.s(c) = key.s(c) Xor key.s(j)
key.s(j) = key.s(c) Xor key.s(j)
key.s(c) = key.s(c) Xor key.s(j)
i = (i + 1) Mod keylen
Next
End Sub
Public Sub rc4(ByRef buff() As Byte, ByRef key As rc4_key)
Dim x As Byte, y As Byte, z As Byte, c As Long, ub As Long, lb As Long
x = key.x
y = key.y
ub = UBound(buff)
lb = LBound(buff)
For c = lb To ub
x = (x + 1) Mod 256
y = ((key.s(x) Mod 256) + y) Mod 256
key.s(x) = key.s(x) Xor key.s(y)
key.s(y) = key.s(x) Xor key.s(y)
key.s(x) = key.s(x) Xor key.s(y)
z = ((key.s(x) Mod 256) + key.s(y)) Mod 256
buff(c) = buff(c) Xor key.s(z)
Next
key.x = x
key.y = y
End Sub
调用的方法 Dim s() As Byte, p() As Byte Dim enkey As rc4_key, denkey As rc4_key s = "1234567890abcdefghijklmnopqrstuvwxyz中文" p = "123abc测试" Call prepare_key(p, enkey) denkey = enkey Call rc4(s, enkey) Call rc4(s, denkey) MsgBox s 如果是多个内容加密,也可以分段解密,或者一次解密全部内容 Dim s() As Byte, p() As Byte Dim enkey As rc4_key, denkey As rc4_key s = "1234567890abcdefghijklmnopqrstuvwxyz中文" p = "123abc测试" Call prepare_key(p, enkey) denkey = enkey Call rc4(s, enkey) Dim s2() As Byte, s3() As Byte s2 = "信息abcd1234" Call rc4(s2, enkey) ReDim s3(0 To UBound(s) + UBound(s2) + 1) Call CopyMemory(s3(0), s(0), UBound(s) + 1) Call CopyMemory(s3(UBound(s) + 1), s2(0), UBound(s2) + 1) Call rc4(s3, denkey) MsgBox s3