Skip to content

Commit 8411855

Browse files
zarqmanfrancescobbo
authored andcommitted
support arbitrary headers during encryption
1 parent 98afc22 commit 8411855

File tree

3 files changed

+27
-1
lines changed

3 files changed

+27
-1
lines changed

README.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,19 @@ plaintext = JWE.decrypt(encrypted, key)
7373
puts plaintext #"The quick brown fox jumps over the lazy dog."
7474
```
7575

76+
This example sets an extra header.
77+
78+
```ruby
79+
require 'jwe'
80+
81+
keys = {
82+
'id-1' => OpenSSL::PKey::RSA.generate(2048)
83+
}
84+
payload = "The quick brown fox jumps over the lazy dog."
85+
86+
encrypted = JWE.encrypt(payload, keys['id-1'], headers: {kid: 'id-1'})
87+
puts encrypted
88+
7689
## Available Algorithms
7790

7891
The RFC 7518 JSON Web Algorithms (JWA) spec defines the algorithms for [encryption](https://tools.ietf.org/html/rfc7518#section-5.1)

lib/jwe.rb

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,14 +19,15 @@ class InvalidData < RuntimeError; end
1919
VALID_ENC = ['A128CBC-HS256', 'A192CBC-HS384', 'A256CBC-HS512', 'A128GCM', 'A192GCM', 'A256GCM'].freeze
2020
VALID_ZIP = ['DEF'].freeze
2121

22-
def self.encrypt(payload, key, alg: 'RSA-OAEP', enc: 'A128GCM', zip: nil)
22+
def self.encrypt(payload, key, alg: 'RSA-OAEP', enc: 'A128GCM', zip: nil, headers: {})
2323
raise ArgumentError.new("\"#{alg}\" is not a valid alg method") unless VALID_ALG.include?(alg)
2424
raise ArgumentError.new("\"#{enc}\" is not a valid enc method") unless VALID_ENC.include?(enc)
2525
raise ArgumentError.new("\"#{zip}\" is not a valid zip method") unless zip.nil? || zip == '' || VALID_ZIP.include?(zip)
2626
raise ArgumentError.new('The key must not be nil or blank') if key.nil? || (key.is_a?(String) && key.strip == '')
2727

2828
header = { alg: alg, enc: enc }
2929
header[:zip] = zip if zip && zip != ''
30+
header.merge!(headers) if headers.is_a?(Hash)
3031

3132
cipher = Enc.for(enc).new
3233
cipher.cek = key if alg == 'dir'

spec/jwe_spec.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,18 @@
2929
end
3030
end
3131

32+
describe 'when using extra headers' do
33+
it 'roundtrips' do
34+
encrypted = JWE.encrypt(plaintext, rsa_key, headers: {kid: 'some-kid-1'})
35+
result = JWE.decrypt(encrypted, rsa_key)
36+
header, _ = JWE::Serialization::Compact.decode(encrypted)
37+
header = JSON.parse(header)
38+
39+
expect(header['kid']).to eq 'some-kid-1'
40+
expect(result).to eq plaintext
41+
end
42+
end
43+
3244
it 'raises when passed a bad alg' do
3345
expect { JWE.encrypt(plaintext, rsa_key, alg: 'TEST') }.to raise_error(ArgumentError)
3446
end

0 commit comments

Comments
 (0)