【字符】RC4 加密解密

  勇芳 2017-4-5 6557

Function RC4(sKey As String, sBuf As String) As String  '// RC4 加密解密(调用它一次加密,再次用相同的密钥来解密)
'// IMPORTANT: // NOT SURE IF THE "MOD"'s SHOULD BE 256 OR 255
'// 需要使用较大的字符串对RC4等软件的输出测试
 #REGISTER None
 Register x As Dword, i As Dword
 Local byte_cipher As Byte, result_ciphered As Byte, byte_msg As Byte Ptr, sOut As String, keylen As Dword, j As Byte
 Dim KBox(255) As Byte, Sbox(255) As Byte '// Key-box和S-box的每个字节尺寸,256(0~255)
 Poke$ VarPtr(KBox(0)), sKey
 keylen = Len(sKey)
 '//初始化S-box。即必须通过 RC4(),每次调用。只是不能将它设置在程序启动时 ; 一次为每个解密需要 reinitialisation。 
 For i = 0 To 255: Sbox(i) = i: Next
 For i = 0 To 255
    j = (j + Sbox(i) + KBox(i Mod keylen)) Mod 255
    Swap Sbox(i), Sbox(j)   '// 我用我自己的 ByteSwap() 为我第一次的 RC4 执行,但 !RDTSC CPU 时间证明 PB 的本机 SWAP() 是大约 10%更快 ;归功于 PB 开发团队 !特别是因为 SWAP() 是灵活的数据类型
 Next i
 '//编码阶段
 j = 0:  byte_msg = StrPtr(sBuf)
 For x = 1 To Len(sBuf)
    i = (i + 1) Mod 255
    j = (j + Sbox(i)) Mod 255
    Swap Sbox(i), Sbox(j)
    byte_cipher = Sbox((Sbox(i) + Sbox(j)) Mod 255)
    result_ciphered = byte_cipher Xor @byte_msg
    Incr byte_msg
    sOut = sOut & Chr$(result_ciphered)
 Next x
 Function = sOut
End Function


因国家互联网安全管理要求,关闭回帖功能。大家需要留言,请使用【勇芳软件客服】即时联系勇芳点此打开->>勇芳软件客服
返回
联系勇芳
发新帖 搜索 反馈 回顶部