Welcome Guest, you are in: Login

Fruit Of The Shed

Navigation (MMBasic)






Search the wiki

»


Page History: RC4 Encryption and Decryption Functions

Compare Page Revisions



« Older Revision - Back to Page History - Current Revision


Page Revision: 2020/06/30 11:53


The RC4 Encryption Algorithm, is a shared key method requiring a secure exchange of a shared key i.e. both sides of the encode/decode must possess the key. RC4 is "symmetrical" - that is the same key is used to both encrypt and decrypt. It is now considered a defunct method for really strong encryption but is still viable with a suitably complex key (at least 30 characters).

RC4$() returns a hexadecimal string of the original input expression. Note: The encrypted string has a 100% overhead in size over the original i.e. it will be twice the length of the input string.

UnRC4$() decodes a previously encrypted hexcadecimal string and returns the original string.

Syntax:
RC4$(expression)
UnRC4$(expression)

Example:
a$=RC4$(password$)
b$=UnRC4$(encrypted_data$)

Assumptions:
  OPTION BASE 0

   ' change this key to whatever you like but it should be complex
   ' at least 30 characters long and don't lose it! To increase security,  
   ' you could use Base64 encoding to obfuscate it in your code. 
   ' It won't stop a determined snooper but why make it easy for them? 
   ' Suitable B64 routines are available in this namespace
  CONST RC4KEY$=">4!1x4q3z4+7%4{9?5\3HhH^5$9=6@1~6,7_7|1)7'3]7[9:8<3*8S9I9l7Z1eT0r1"

Code:
  Function RC4$(z$)
    Local String outp,b
    Local Integer i,j,x,y,t,temp,s(255),k(255)

    For i=0 To 255: s(i)=i: Next
    
    j=1
    For i=0 To 255
      if j>Len(RC4key$) Then j=1
      k(i)=Asc(Mid$(RC4key$, j, 1))
      j=j+1
    Next

    j=0
    For i=0 To 255
      j=(j+s(i)+k(i)) Mod 256
      temp=s(i): s(i)=s(j): s(j)=temp
    Next

    i=0: j=0
    For x=1 To Len(z$)
      i=(i+1) Mod 256: j=(j+s(i)) Mod 256
      temp=s(i): s(i)=s(j): s(j)=temp
      t=(s(i)+(s(j) Mod 256)) Mod 256: y=s(t)
      outp=outp+Chr$(Asc(Mid$(z$, x, 1)) Xor y)
    Next

    b="": j=0
    For x=1 To Len(outp)
      b=b+Hex$(Asc(Mid$(outp, x, 1)), 2): j=j+Asc(Mid$(outp, x, 1))
    Next

    RC4$=b
  End Function

  Function UnRC4$(z$)
    Local String mystr,a,b
    Local Integer n
    mystr=""
    For n=1 To Len(z$) Step 2
      a=Mid$(z$, n, 2)
      a=Chr$(Val("&h"+a))
      mystr=mystr+a
    Next
    mystr=RC4$(mystr)
    b=""
    For n=1 To Len(mystr) Step 2
      a=Mid$(mystr, n, 2)
      a=Chr$(Val("&h"+a))
      b=b+a
    Next
    UnRC4$=b
  End Function