Class: Crypt::RC6

Inherits:
Object
  • Object
show all
Includes:
CBC
Defined in:
lib/crypt/rc6.rb

Constant Summary

Constants included from CBC

CBC::ULONG

Instance Method Summary collapse

Methods included from CBC

#carefully_open_file, #decrypt_file, #decrypt_stream, #decrypt_string, #encrypt_file, #encrypt_stream, #encrypt_string, #generate_initialization_vector

Constructor Details

#initialize(key) ⇒ RC6

Returns a new instance of RC6.



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/crypt/rc6.rb', line 25

def initialize(key)
  @rounds, @sbox, @key = 20, [0xB7E15163], []
  key = key.bytes.to_a if key.class == String
  raise("Wrong key length") unless [32,24,16].include?(key.size)
  (key.size-1).downto(0){|i| @key[i/4] = ((@key[i/4]||0) << 8) + key[i]}

  (@rounds * 2 + 3).times{|i| @sbox << (@sbox.last + 0x9E3779B9 & 0xffffffff)}
  a = b = i = j = 0
  (3 * (2 * @rounds + 4)).times do
    a = @sbox[i] = lrotate(@sbox[i] + a + b, 3)
    b = @key[j] = lrotate(@key[j] + a + b, a + b)
    i = (i + 1).divmod(2 * @rounds + 4).last
    j = (j + 1).divmod(@key.size).last
  end
end

Instance Method Details

#block_sizeObject



12
13
14
# File 'lib/crypt/rc6.rb', line 12

def block_size
  return 16
end

#decrypt_block(data) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/crypt/rc6.rb', line 57

def decrypt_block(data)
  a, b, c, d = *data.unpack('N*')
  c -= @sbox[2 * @rounds + 3]
  a -= @sbox[2 * @rounds + 2]
  @rounds.downto 1 do |i|
    a, b, c, d = d, a, b, c
    u = lrotate((d * (2 * d + 1)), 5)
    t = lrotate((b * (2 * b + 1)), 5)
    c = rrotate((c - @sbox[2 * i + 1]), t) ^ u
    a = rrotate((a - @sbox[2 * i]), u) ^ t
  end
  d -= @sbox[1]
  b -= @sbox[0]
  [a, b, c, d].map{|i| i & 0xffffffff}.pack('N*')
end

#encrypt_block(data) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/crypt/rc6.rb', line 41

def encrypt_block(data)
  a, b, c, d = *data.unpack('N*')
  b += @sbox[0]
  d += @sbox[1]
  1.upto @rounds do |i|
    t = lrotate((b * (2 * b + 1)), 5)
    u = lrotate((d * (2 * d + 1)), 5)
    a = lrotate((a ^ t), u) + @sbox[2 * i]
    c = lrotate((c ^ u), t) + @sbox[2 * i + 1]
    a, b, c, d  =  b, c, d, a
  end
  a += @sbox[2 * @rounds + 2]
  c += @sbox[2 * @rounds + 3]
  [a, b, c, d].map{|i| i & 0xffffffff}.pack('N*')
end

#lrotate(d, s) ⇒ Object



16
17
18
19
# File 'lib/crypt/rc6.rb', line 16

def lrotate(d,s)
  d = d & 0xffffffff
  ((d)<<(s&(31))) | ((d)>>(32-(s&(31))))
end

#rrotate(d, s) ⇒ Object



20
21
22
23
# File 'lib/crypt/rc6.rb', line 20

def rrotate(d,s)
  d = d & 0xffffffff
  ((d)>>(s&(31))) | ((d)<<(32-(s&(31))))
end