Fast encryption

version 6 from

Function rc4v6(dataString as string, keyString as string) As string
  // highly optimized version of the RC4 algorithm written for Xojo 2014 
  // uses pointers and MemoryBlocks for speed
  // written to follow the pseudo-code algorithm described here:  http://en.wikipedia.org/wiki/Rc4
  #Pragma DisableBackgroundTasks
  #Pragma DisableBoundsChecking
  #Pragma NilObjectChecking False
  #Pragma StackOverflowChecking False
  
  
  Dim mbPlaintext as MemoryBlock = dataString  // input data
  dim Plaintext as Ptr = mbPlaintext // a pointer, used for speed
  
  Dim mbCyphertext as New MemoryBlock(mbPlaintext.Size)    // output data, same size as input
  dim Cyphertext as Ptr = mbCyphertext // a pointer, used for speed
  
  dim mbKey as MemoryBlock = keyString  // the key, as a MemoryBlock
  dim Key as Ptr = mbKey
  
  dim keylength as integer = mbKey.size
  
  
  // do the Key Scheduling Algorithm (KSA)
  dim mbS as new MemoryBlock(256)
  dim S as Ptr = mbS // a pointer, used for speed
  
  // first, fill it with Identity (0-255)
  for i as integer = 0 to 255
    S.byte(i) = i
  next
  
  // now, do the KSA
  dim i,j as integer
  for i = 0 to 255
    j = (j + S.byte(i) + Key.byte(i mod keylength) ) mod 256
    // swap values of S[i] and S[j]
    dim tmp as Byte = S.byte(j)
    S.byte(j) = S.byte(i)
    S.byte(i) = tmp
  next
  
  
  // now, do the encoding
  i = 0
  j = 0
  
  dim U as integer = mbPlaintext.Size-1 // iterate from 0...U
  for x as integer = 0 to U
    i= (i + 1 ) mod 256
    j = (j + S.byte(i) ) mod 256
    // swap values of S[i] and S[j]
    dim tmp as Byte = S.byte(j)
    S.byte(j) = S.byte(i)
    S.byte(i) = tmp
    
    // K is the keystream value which is XORed with the Plaintext to make the Cyphertext
    dim K as Byte  = S.byte( (S.byte(i) + S.byte(j))  mod 256)
    
    Cyphertext.byte(x) = Plaintext.byte(x) XOR K
  next
  
  return mbCyphertext
End Function