Skip to content

Instantly share code, notes, and snippets.

@unsign3d
Last active August 29, 2015 13:56
Show Gist options
  • Save unsign3d/9118104 to your computer and use it in GitHub Desktop.
Save unsign3d/9118104 to your computer and use it in GitHub Desktop.
rc4 not standard implementation
#!/usr/bin/env ruby
# simple RC4 implementation
# NO WARRANTY, IT COULD BE WRONG
def rc4 (str_key, str_plaintext)
## KSA
#holding key and plaintext
key = str_key.bytes
plaintext = str_plaintext.bytes
# create output
output = Array.new(plaintext.length)
#sbox initialized with 0..255 values
sbox = Array.new(256) { |i| i+1}
#input length
kl = key.length
tl = plaintext.length
#j index
j = 0
# so preparation
255.times do | i |
#such shifting
j = (j + sbox[i] + key[i % kl]) % 256
#so swap
sbox[i], sbox[j] = sbox[j], sbox[i]
end
## /KSA
## PRGA
i = 0
j = 0
tl.times do | v |
i = (i + 1) % 256
j = (j + sbox[i]) % 256
sbox[i], sbox[j] = sbox[j], sbox[i]
output[v] = sbox[(sbox[i] + sbox[j]) % 256] ^ plaintext[v]
end
## /PRGA
out_string = ""
key_string = ""
output.each do | v |
out_string = out_string + sprintf("%X", v)
end
return out_string
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment