Android Example RC4 encryption to transfer data between Android and PC

Hi,

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!
 

Attachments

  • rc4.zip
    47 KB · Views: 511
Last edited:

valerioup

Member
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

B4X:
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
    Next


    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)))
       
    Next

    For lI = 0 To 255
        lJ = (lJ + baS(lI) + baK(lI)) Mod 256       
        bytSwap = baS(lI)
        baS(lI) = baS(lJ)
        baS(lJ) = bytSwap
    Next
    lI = 0
    lJ = 0
    Log(Text2.Length)
    For lIdx = 1 To text.ToUpperCase.Length/2
        lI = (lI + 1) Mod 256
        lJ = (lJ + baS(lI)) Mod 256
        Log(lJ)
        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))
        Else
            cipherby = (Bit.Xor(baS(((baS(lI)) + baS(lJ)) Mod 256), Asc(sf.MID(Text2, lIdx, 1))))
        End If
        

        cipher = cipher & Chr(cipherby)
        
    Next


    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
 
Top