Class: Sandal::Enc::AGCM
- Inherits:
-
Object
- Object
- Sandal::Enc::AGCM
- Defined in:
- lib/sandal/enc/agcm.rb
Overview
Base implementation of the A*GCM family of encryption methods.
Constant Summary collapse
- @@iv_size =
96
- @@auth_tag_size =
128
Instance Attribute Summary collapse
-
#alg ⇒ Object
readonly
The JWA algorithm used to encrypt the content encryption key.
-
#name ⇒ Object
readonly
The JWA name of the encryption method.
Instance Method Summary collapse
-
#decrypt(token) ⇒ String
Decrypts an encrypted JSON Web Token.
-
#encrypt(header, payload) ⇒ String
Encrypts a token payload.
-
#initialize(name, aes_size, alg) ⇒ AGCM
constructor
Initialises a new instance; it’s probably easier to use one of the subclass constructors.
Constructor Details
#initialize(name, aes_size, alg) ⇒ AGCM
Initialises a new instance; it’s probably easier to use one of the subclass constructors.
23 24 25 26 27 28 |
# File 'lib/sandal/enc/agcm.rb', line 23 def initialize(name, aes_size, alg) @name = name @aes_size = aes_size @cipher_name = "aes-#{aes_size}-gcm" @alg = alg end |
Instance Attribute Details
#alg ⇒ Object (readonly)
The JWA algorithm used to encrypt the content encryption key.
17 18 19 |
# File 'lib/sandal/enc/agcm.rb', line 17 def alg @alg end |
#name ⇒ Object (readonly)
The JWA name of the encryption method.
14 15 16 |
# File 'lib/sandal/enc/agcm.rb', line 14 def name @name end |
Instance Method Details
#decrypt(token) ⇒ String
Decrypts an encrypted JSON Web Token.
56 57 58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/sandal/enc/agcm.rb', line 56 def decrypt(token) parts, decoded_parts = Sandal::Enc.token_parts(token) cipher = OpenSSL::Cipher.new(@cipher_name).decrypt begin cipher.key = @alg.decrypt_key(decoded_parts[1]) cipher.iv = decoded_parts[2] cipher.auth_tag = decoded_parts[4] cipher.auth_data = parts[0] cipher.update(decoded_parts[3]) + cipher.final rescue OpenSSL::Cipher::CipherError => e raise Sandal::InvalidTokenError, "Cannot decrypt token: #{e.}" end end |
#encrypt(header, payload) ⇒ String
Encrypts a token payload.
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/sandal/enc/agcm.rb', line 35 def encrypt(header, payload) cipher = OpenSSL::Cipher.new(@cipher_name).encrypt key = @alg.respond_to?(:preshared_key) ? @alg.preshared_key : cipher.random_key encrypted_key = @alg.encrypt_key(key) cipher.key = key cipher.iv = iv = SecureRandom.random_bytes(@@iv_size / 8) auth_data = Sandal::Util.jwt_base64_encode(header) cipher.auth_data = auth_data ciphertext = cipher.update(payload) + cipher.final remaining_parts = [encrypted_key, iv, ciphertext, cipher.auth_tag(@@auth_tag_size / 8)] remaining_parts.map! { |part| Sandal::Util.jwt_base64_encode(part) } [auth_data, *remaining_parts].join(".") end |