Class: Sandal::Enc::AGCM
- Inherits:
-
Object
- Object
- Sandal::Enc::AGCM
- Defined in:
- lib/sandal/enc/agcm.rb
Overview
Base implementation of the AES/GCM family of encryption algorithms.
Instance Attribute Summary collapse
-
#alg ⇒ Object
readonly
The JWA algorithm used to encrypt the content master key.
-
#name ⇒ Object
readonly
The JWA name of the encryption.
Instance Method Summary collapse
- #decrypt(parts, decoded_parts) ⇒ Object
- #encrypt(header, payload) ⇒ Object
-
#initialize(aes_size, alg) ⇒ AGCM
constructor
A new instance of AGCM.
Constructor Details
#initialize(aes_size, alg) ⇒ AGCM
Returns a new instance of AGCM.
16 17 18 19 20 21 |
# File 'lib/sandal/enc/agcm.rb', line 16 def initialize(aes_size, alg) @aes_size = aes_size @name = "A#{aes_size}GCM" @cipher_name = "aes-#{aes_size}-gcm" @alg = alg end |
Instance Attribute Details
#alg ⇒ Object (readonly)
The JWA algorithm used to encrypt the content master key.
14 15 16 |
# File 'lib/sandal/enc/agcm.rb', line 14 def alg @alg end |
#name ⇒ Object (readonly)
The JWA name of the encryption.
11 12 13 |
# File 'lib/sandal/enc/agcm.rb', line 11 def name @name end |
Instance Method Details
#decrypt(parts, decoded_parts) ⇒ Object
40 41 42 43 44 45 46 47 |
# File 'lib/sandal/enc/agcm.rb', line 40 def decrypt(parts, decoded_parts) cipher = OpenSSL::Cipher.new(@cipher_name).decrypt cipher.key = @alg.decrypt_cmk(decoded_parts[1]) cipher.iv = decoded_parts[2] cipher.auth_tag = decoded_parts[4] cipher.auth_data = parts.take(3).join('.') cipher.update(decoded_parts[3]) + cipher.final end |
#encrypt(header, payload) ⇒ Object
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/sandal/enc/agcm.rb', line 23 def encrypt(header, payload) cipher = OpenSSL::Cipher.new(@cipher_name).encrypt content_master_key = @alg.respond_to?(:cmk) ? @alg.cmk : cipher.random_key encrypted_key = @alg.encrypt_cmk(content_master_key) cipher.key = content_master_key iv = cipher.random_iv auth_parts = [MultiJson.dump(header), encrypted_key, iv] auth_data = auth_parts.map { |part| Sandal::Util.base64_encode(part) }.join('.') cipher.auth_data = auth_data ciphertext = cipher.update(payload) + cipher.final remainder = [ciphertext, cipher.auth_tag].map { |part| Sandal::Util.base64_encode(part) }.join('.') [auth_data, remainder].join('.') end |