Guest User

Untitled

a guest
Jan 15th, 2013
865
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. --[[ RC4 Encryption - NeverCast
  2. --]]
  3.  
  4. local function swapStateIndicies( state )
  5.     local t = state.schedule[state.i]
  6.     state.schedule[state.i] = state.schedule[state.j]
  7.     state.schedule[state.j] = t
  8. end
  9.  
  10. local function swapIndicies( sch, i, j )
  11.     local t = sch[i]
  12.     sch[i] = sch[j]
  13.     sch[j] = t
  14. end
  15.  
  16. local function createKeySchedule( sKey )
  17.   local nKeyLength = string.len(sKey)
  18.   local tKey = { string.byte( sKey, 1, nKeyLength) }
  19.   if nKeyLength < 1 or nKeyLength > 256 then
  20.     error("Key length out of bounds. 1 <= length <= 256")
  21.   end
  22.   local tSch = {}
  23.   for i = 0, 255 do
  24.     tSch[i] = i
  25.   end
  26.   local j = 0
  27.   for i = 0, 255 do
  28.     j = ( j + tSch[i] + tKey[(i % nKeyLength) + 1]) % 256
  29.     swapIndicies( tSch, i, j )
  30.   end
  31.   return tSch
  32. end
  33.  
  34. local function keyGeneration( state, nCount )
  35.   local K = {}
  36.   for i = 1, nCount do
  37.     state.i = ( state.i + 1) % 256
  38.     state.j = ( state.j + state.schedule[state.i - 1]) % 256
  39.     swapStateIndicies( state )
  40.     K[#K+1] = state.schedule[ ( state.schedule[ state.i - 1] + state.schedule[ state.j - 1] - 1)  % 256]
  41.   end
  42.   return K
  43. end
  44.  
  45. local function cipher( sMessage, state)
  46.   local nCount = string.len(sMessage)
  47.   local K = keyGeneration( state, nCount )
  48.   local sOutput = ""
  49.   for i = 1, nCount do
  50.     sOutput = sOutput .. string.char( bit.bxor( K[i], string.byte(sMessage, i)))
  51.   end
  52.   return sOutput
  53. end
  54.  
  55. function new( sKey, bEncryption )
  56.   local tSch = createKeySchedule( sKey )
  57.   local nS1 = 0
  58.   local nS2 = 0
  59.   local state = {
  60.     i = nS1,
  61.     j = nS2,
  62.     schedule = tSch
  63.   }
  64.   local tSession = {}
  65.   local sFuncName = "decrypt"
  66.   if bEncryption then
  67.     sFuncName = "encrypt"
  68.   end
  69.   tSession[sFuncName] = function( sMessage )
  70.     local sOutput = cipher( sMessage, state)
  71.     return sOutput
  72.   end
  73.   return tSession
  74. end
RAW Paste Data