Class: Present::Cipher

Inherits:
Object
  • Object
show all
Defined in:
lib/present/cipher.rb,
lib/present/cipher/error.rb,
lib/present/cipher/version.rb

Defined Under Namespace

Classes: BlockError, Error, KeyError, NotSupportedError

Constant Summary collapse

KEY_BITSIZE_80 =
80
KEY_BITSIZE_128 =
128
BLOCK_BITSIZE =
64
KEY_BYTESIZE_80 =
KEY_BITSIZE_80 / 8
KEY_BYTESIZE_128 =
KEY_BITSIZE_128 / 8
BLOCK_BYTESIZE =
BLOCK_BITSIZE / 8
S_BOX =
[
  0x0C, 0x05, 0x06, 0x0b, 0x09, 0x00, 0x0a, 0x0d, 0x03, 0x0e, 0x0f, 0x08, 0x04, 0x07, 0x01, 0x02,
]
INVERSE_S_BOX =
0.upto(S_BOX.length - 1).map { |n| S_BOX.index(n) }
P_BOX =
[
  0x00, 0x10, 0x20, 0x30, 0x01, 0x11, 0x21, 0x31, 0x02, 0x12, 0x22, 0x32, 0x03, 0x13, 0x23, 0x33,
  0x04, 0x14, 0x24, 0x34, 0x05, 0x15, 0x25, 0x35, 0x06, 0x16, 0x26, 0x36, 0x07, 0x17, 0x27, 0x37,
  0x08, 0x18, 0x28, 0x38, 0x09, 0x19, 0x29, 0x39, 0x0a, 0x1a, 0x2a, 0x3a, 0x0b, 0x1b, 0x2b, 0x3b,
  0x0c, 0x1c, 0x2c, 0x3c, 0x0d, 0x1d, 0x2d, 0x3d, 0x0e, 0x1e, 0x2e, 0x3e, 0x0f, 0x1f, 0x2f, 0x3f,
]
INVERSE_P_BOX =
0.upto(P_BOX.length - 1).map { |n| P_BOX.index(n) }
VERSION =
"1.0.0"

Instance Method Summary collapse

Constructor Details

#initialize(key) ⇒ Cipher

Returns a new instance of Cipher.



31
32
33
34
35
# File 'lib/present/cipher.rb', line 31

def initialize(key)
  validate(key, as: :key)

  @key = key.dup
end

Instance Method Details

#decrypt(bytes) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/present/cipher.rb', line 53

def decrypt(bytes)
  validate(bytes, as: :block)

  bits = bytes.unpack1("Q>")

  31.downto(1) do |i|
    bits = apply_round_key(bits, round_keys[i])
    bits = apply_permutation_box(bits, INVERSE_P_BOX)
    bits = apply_substitution_box(bits, INVERSE_S_BOX)
  end

  bits = apply_round_key(bits, round_keys[0])

  [bits].pack("Q>")
end

#encrypt(bytes) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/present/cipher.rb', line 37

def encrypt(bytes)
  validate(bytes, as: :block)

  bits = bytes.unpack1("Q>")

  0.upto(30) do |i|
    bits = apply_round_key(bits, round_keys[i])
    bits = apply_substitution_box(bits, S_BOX)
    bits = apply_permutation_box(bits, P_BOX)
  end

  bits = apply_round_key(bits, round_keys[31])

  [bits].pack("Q>")
end