1. 程式人生 > >VB的RC4加密演算法,支援中文

VB的RC4加密演算法,支援中文

    最近需要用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