Module: JWE::Alg::AesKw

Included in:
A128kw, A192kw, A256kw
Defined in:
lib/jwe/alg/aes_kw.rb

Overview

Generic AES Key Wrapping algorithm for any key size.

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#ivObject

Returns the value of attribute iv.



8
9
10
# File 'lib/jwe/alg/aes_kw.rb', line 8

def iv
  @iv
end

#keyObject

Returns the value of attribute key.



7
8
9
# File 'lib/jwe/alg/aes_kw.rb', line 7

def key
  @key
end

Instance Method Details

#a_ri(b) ⇒ Object



65
66
67
# File 'lib/jwe/alg/aes_kw.rb', line 65

def a_ri(b)
  [b.first(8).join, b.last(8).join]
end

#cipherObject



69
70
71
# File 'lib/jwe/alg/aes_kw.rb', line 69

def cipher
  @cipher ||= Enc::Cipher.for(cipher_name)
end

#decrypt(encrypted_cek) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/jwe/alg/aes_kw.rb', line 38

def decrypt(encrypted_cek)
  c = encrypted_cek.force_encoding('ASCII-8BIT').scan(/.{8}/m)
  a, *r = c

  5.downto(0) do |j|
    a, r = kw_decrypt_round(j, a, r)
  end

  if a != iv
    raise StandardError.new('The encrypted key has been tampered. Do not use this key.')
  end

  r.join
end

#decrypt_round(data) ⇒ Object



80
81
82
83
84
85
# File 'lib/jwe/alg/aes_kw.rb', line 80

def decrypt_round(data)
  cipher.decrypt
  cipher.key = key
  cipher.padding = 0
  cipher.update(data) + cipher.final
end

#encrypt(cek) ⇒ Object



15
16
17
18
19
20
21
22
23
24
# File 'lib/jwe/alg/aes_kw.rb', line 15

def encrypt(cek)
  a = iv
  r = cek.force_encoding('ASCII-8BIT').scan(/.{8}/m)

  6.times do |j|
    a, r = kw_encrypt_round(j, a, r)
  end

  ([a] + r).join
end

#encrypt_round(data) ⇒ Object



73
74
75
76
77
78
# File 'lib/jwe/alg/aes_kw.rb', line 73

def encrypt_round(data)
  cipher.encrypt
  cipher.key = key
  cipher.padding = 0
  cipher.update(data) + cipher.final
end

#initialize(key = nil, iv = "\xA6\xA6\xA6\xA6\xA6\xA6\xA6\xA6") ⇒ Object



10
11
12
13
# File 'lib/jwe/alg/aes_kw.rb', line 10

def initialize(key = nil, iv = "\xA6\xA6\xA6\xA6\xA6\xA6\xA6\xA6")
  self.iv = iv.force_encoding('ASCII-8BIT')
  self.key = key.force_encoding('ASCII-8BIT')
end

#kw_decrypt_round(j, a, r) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
# File 'lib/jwe/alg/aes_kw.rb', line 53

def kw_decrypt_round(j, a, r)
  r.length.downto(1) do |i|
    a = xor(a, (r.length * j) + i)

    b = decrypt_round(a + r[i - 1]).chars

    a, r[i - 1] = a_ri(b)
  end

  [a, r]
end

#kw_encrypt_round(j, a, r) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/jwe/alg/aes_kw.rb', line 26

def kw_encrypt_round(j, a, r)
  r.length.times do |i|
    b = encrypt_round(a + r[i]).chars

    a, r[i] = a_ri(b)

    a = xor(a, (r.length * j) + i + 1)
  end

  [a, r]
end

#xor(data, t) ⇒ Object



87
88
89
90
91
92
# File 'lib/jwe/alg/aes_kw.rb', line 87

def xor(data, t)
  t = ([0] * (data.length - 1)) + [t]
  data = data.chars.map(&:ord)

  data.zip(t).map { |a, b| (a ^ b).chr }.join
end