Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- ARC4
- -- By KillaVanilla
- -- Hey, go figure! I actually *was* able to write this on my own!
- -- Best practice with RC4 (and stream ciphers in general, IIRC) is to combine your key and nonce (concentation works), then hash the combined result, and use that as the key.
- local rc4_object = {
- s = {},
- i = 0,
- j = 0,
- key_schedule = function(self, key)
- for i=0, 255 do
- self.s[i] = i
- end
- self.j = 0
- for i=0, 255 do
- self.j = (self.j + self.s[i] + key[(i % #key)+1]) % 256
- local temp = self.s[i]
- self.s[i] = self.s[self.j]
- self.s[self.j] = temp
- end
- end,
- set_key = function(self, key)
- if type(key) == "string" then
- if #key == 0 then
- error("rc4-set_key: Invalid key length!", 2)
- end
- if #key > 256 then
- self:key_schedule({string.byte(key, 1, 256)})
- else
- self:key_schedule({string.byte(key, 1, #key)})
- end
- elseif type(key) == "table" then
- local filteredKey = {}
- for i=1, #key do
- if (type(key[i]) == "number") and ((key[i] >= 0) and (key[i] <= 255)) then
- table.insert(filteredKey, key[i])
- if #filteredKey >= 256 then
- break
- end
- end
- end
- if #filteredKey == 0 then
- error("rc4-set_key: Invalid key length!", 2)
- end
- self:key_schedule(filteredKey)
- end
- end,
- generate_byte = function(self)
- self.i = (self.i + 1) % 256
- self.j = (self.j+self.s[self.i]) % 256
- local temp = self.s[self.i]
- self.s[self.i] = self.s[self.j]
- self.s[self.j] = temp
- local k = self.s[(self.s[self.i] + self.s[self.j]) % 256]
- return k
- end,
- discard_bytes = function(self, n)
- for i=1, n do
- self:generate_byte()
- end
- end,
- crypt_array = function(self, iArray)
- local oArray = {}
- local lastPause = os.clock()
- for ctr=1, #iArray do
- local keystream = self:generate_byte()
- oArray[ctr] = bit.bxor(keystream, iArray[ctr])
- if (os.clock() - lastPause) >= 2.90 then
- os.queueEvent("")
- os.pullEvent("")
- lastPause = os.clock()
- end
- end
- return oArray
- end,
- crypt_string = function(self, iStr)
- local oStr = ""
- local oArray = {}
- local lastPause = os.clock()
- for ctr=1, #iStr do
- local keystream = self:generate_byte()
- oArray[ctr] = bit.bxor(keystream, string.byte(iStr, ctr, ctr))
- oStr = oStr..string.char(oArray[ctr])
- if (os.clock() - lastPause) >= 2.90 then
- os.queueEvent("")
- os.pullEvent("")
- lastPause = os.clock()
- end
- end
- return oStr, oArray
- end,
- }
- function new_rc4_object(key)
- local cxt = {}
- for i,v in pairs(rc4_object) do
- cxt[i] = v
- end
- cxt:set_key(key)
- cxt:discard_bytes(3072)
- return cxt
- end
- function encrypt(data, key)
- local object = new_rc4_object(key)
- if type(data) == "string" then
- return object:crypt_string(data)
- elseif type(data) == "table" then
- return object:crypt_array(data)
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement