Android Example RC4 encryption to transfer data between Android and PC


On one of my projects, I had to transfer sensitive data from Android to PC but - with RC4 encription.
I wrote a little code that I want to share with you...
Maybe Android supports RC4 encryption in some of its libs, I'm not sure, but this code may be usefull for someone.
This code is not mine, I just rewrite it to B4A :)

You have to add StringFunctions.
Best regards!


    47 KB · Views: 435
Last edited:


Licensed User
Longtime User
if an encrypted string arrives from an application for PC or .net the decoding function is not correct.
I rewrote the feature

Sub RC4Decrypt2(text As String, encryptkey As String)
    Dim sbox(256)
    Dim key(256)
    Dim Text2 As String
    Dim temp As Int
    Dim a As Long
    Dim i As Int
    Dim j As Int
    Dim k As Long
    Dim w As Int
    Dim cipherby As Int
    Dim cipher As String
    For w = 1 To text.ToUpperCase.Length Step 2
'        Text2 = Text2 & Chr(Dec(sf.Mid(text, w, 2)))
        Dim tmpL
        tmpL = sf.Mid(text, w, 2)
        Dim tmpD
        tmpD = Dec(tmpL)
        Dim tmpC
        tmpC = Chr(tmpD)
        Text2 = Text2 & tmpC

    Dim baS(256) As Int
    Dim baK(256) As Int
    Dim bytSwap     As Int
    Dim lI          As Long
    Dim lJ          As Long
    Dim lIdx        As Long

    For lIdx = 0 To 255
        baS(lIdx) = lIdx
        baK(lIdx) = Asc(encryptkey.CharAt(  (lIdx Mod encryptkey.Length)))

    For lI = 0 To 255
        lJ = (lJ + baS(lI) + baK(lI)) Mod 256       
        bytSwap = baS(lI)
        baS(lI) = baS(lJ)
        baS(lJ) = bytSwap
    lI = 0
    lJ = 0
    For lIdx = 1 To text.ToUpperCase.Length/2
        lI = (lI + 1) Mod 256
        lJ = (lJ + baS(lI)) Mod 256
        bytSwap = baS(lI)
        baS(lI) = baS(lJ)
        baS(lJ) = bytSwap
        If Asc(sf.MID(Text2, lIdx, 1))=baS(((baS(lI)) + baS(lJ)) Mod 256) Then
            cipherby= Asc(sf.MID(Text2, lIdx, 1))
            cipherby = (Bit.Xor(baS(((baS(lI)) + baS(lJ)) Mod 256), Asc(sf.MID(Text2, lIdx, 1))))
        End If

        cipher = cipher & Chr(cipherby)

    Return cipher

End Sub

the problem is in the xor function that should be performed only if the two parts are different otherwise it would result in 0.
I hope it can help those who have had problems with rc4 decoding