Skip to content

Commit 3444db0

Browse files
committed
Reduces AESKW complexity
1 parent 9317c77 commit 3444db0

2 files changed

Lines changed: 34 additions & 22 deletions

File tree

lib/jwe/alg.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
require 'jwe/alg/a128_kw'
2+
require 'jwe/alg/a192_kw'
3+
require 'jwe/alg/a256_kw'
24
require 'jwe/alg/dir'
35
require 'jwe/alg/rsa_oaep'
46
require 'jwe/alg/rsa15'

lib/jwe/alg/aes_kw.rb

Lines changed: 32 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -14,39 +14,33 @@ def initialize(key = nil, iv = "\xA6\xA6\xA6\xA6\xA6\xA6\xA6\xA6")
1414

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

1919
6.times do |j|
20-
r.length.times do |i|
21-
b = encrypt_round(a + r[i])
22-
23-
a = b.chars.first(8).join
24-
r[i] = b.chars.last(8).join
25-
26-
t = (r.length * j) + i + 1
27-
a = xor(a, t)
28-
end
20+
a, r = kw_encrypt_round(j, a, r)
2921
end
3022

3123
([a] + r).join
3224
end
3325

34-
def decrypt(encrypted_cek)
35-
c = encrypted_cek.scan(/.{8}/m)
36-
a = c[0]
26+
def kw_encrypt_round(j, a, r)
27+
r.length.times do |i|
28+
b = encrypt_round(a + r[i]).chars
3729

38-
r = c[1..c.length]
30+
a, r[i] = a_ri(b)
3931

40-
5.downto(0) do |j|
41-
r.length.downto(1) do |i|
42-
t = (r.length * j) + i
43-
a = xor(a, t)
32+
a = xor(a, (r.length * j) + i + 1)
33+
end
4434

45-
b = decrypt_round(a + r[i - 1])
35+
[a, r]
36+
end
37+
38+
def decrypt(encrypted_cek)
39+
c = encrypted_cek.force_encoding('ASCII-8BIT').scan(/.{8}/m)
40+
a, *r = c
4641

47-
a = b.chars.first(8).join
48-
r[i - 1] = b.chars.last(8).join
49-
end
42+
5.downto(0) do |j|
43+
a, r = kw_decrypt_round(j, a, r)
5044
end
5145

5246
if a != iv
@@ -56,6 +50,22 @@ def decrypt(encrypted_cek)
5650
r.join
5751
end
5852

53+
def kw_decrypt_round(j, a, r)
54+
r.length.downto(1) do |i|
55+
a = xor(a, (r.length * j) + i)
56+
57+
b = decrypt_round(a + r[i - 1]).chars
58+
59+
a, r[i - 1] = a_ri(b)
60+
end
61+
62+
[a, r]
63+
end
64+
65+
def a_ri(b)
66+
[b.first(8).join, b.last(8).join]
67+
end
68+
5969
def cipher
6070
@cipher ||= Enc::Cipher.for(cipher_name)
6171
end

0 commit comments

Comments
 (0)