Class: Ciphr::Functions::Crypto::RC4Cipher

Inherits:
InvertibleFunction show all
Defined in:
lib/ciphr/functions/crypto.rb

Instance Attribute Summary

Attributes inherited from InvertibleFunction

#invert

Attributes inherited from Function

#args, #options

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from InvertibleFunction

invertable?

Methods inherited from Function

aligned, inherited, #initialize, invertable?, #prepend, #read

Constructor Details

This class inherits a constructor from Ciphr::Functions::Function

Class Method Details

.paramsObject



38
39
40
# File 'lib/ciphr/functions/crypto.rb', line 38

def self.params 
  [:input, :key]
end

.variantsObject



34
35
36
# File 'lib/ciphr/functions/crypto.rb', line 34

def self.variants
  [[['rc4-ruby'],{}]]
end

Instance Method Details

#applyObject



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/ciphr/functions/crypto.rb', line 3

def apply
  input, key = @args
  keybytes = key.read.unpack('c*')
  s = (0..255).to_a
  j = 0
  (0..255).each do |i|
    j = (j + s[i] + keybytes[i % keybytes.size]) % 256
    swp = s[i]
    s[i] = s[j]
    s[j] = swp
  end
  i = 0
  j = 0

  Proc.new do
    byte = input.read(1)
    if byte
      i = (i + 1) % 256
      j = (j + s[i]) % 256
      swp = s[i]
      s[i] = s[j]
      s[j] = swp
      k = s[(s[i] + s[j]) % 256]
      m = [(byte.unpack('c*')[0] ^ k)].pack('c*') 
      m
    else
      nil
    end
  end
end