Class: Sandal::Enc::ACBC_HS

Inherits:
Object
  • Object
show all
Defined in:
lib/sandal/enc/acbc_hs.rb

Overview

Base implementation of the AES/CBC+HMAC-SHA family of encryption algorithms.

Direct Known Subclasses

A128CBC_HS256, A256CBC_HS512

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(aes_size, sha_size, alg) ⇒ ACBC_HS

Creates a new instance; it’s probably easier to use one of the subclass constructors.

Parameters:

  • aes_size (Integer)

    The size of the AES algorithm.

  • sha_size (Integer)

    The size of the SHA algorithm.

  • key (#name, #encrypt_cmk, #decrypt_cmk)

    The algorithm to use to encrypt and/or decrypt the AES key.



21
22
23
24
25
26
27
28
# File 'lib/sandal/enc/acbc_hs.rb', line 21

def initialize(aes_size, sha_size, alg)
  @aes_size = aes_size
  @sha_size = sha_size
  @name = "A#{aes_size}CBC+HS#{@sha_size}"
  @cipher_name = "aes-#{aes_size}-cbc"
  @alg = alg
  @digest = OpenSSL::Digest.new("sha#{@sha_size}")
end

Instance Attribute Details

#algObject (readonly)

The JWA algorithm used to encrypt the content master key.



14
15
16
# File 'lib/sandal/enc/acbc_hs.rb', line 14

def alg
  @alg
end

#nameObject (readonly)

The JWA name of the encryption.



11
12
13
# File 'lib/sandal/enc/acbc_hs.rb', line 11

def name
  @name
end

Instance Method Details

#decrypt(parts, decoded_parts) ⇒ Object

Raises:



47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/sandal/enc/acbc_hs.rb', line 47

def decrypt(parts, decoded_parts)
  content_master_key = @alg.decrypt_cmk(decoded_parts[1])
  
  content_integrity_key = derive_integrity_key(content_master_key)
  computed_integrity_value = compute_integrity_value(content_integrity_key, parts.take(4).join('.'))
  raise Sandal::TokenError, 'Invalid integrity value.' unless decoded_parts[4] == computed_integrity_value

  cipher = OpenSSL::Cipher.new(@cipher_name).decrypt
  cipher.key = derive_encryption_key(content_master_key)
  cipher.iv = decoded_parts[2]
  cipher.update(decoded_parts[3]) + cipher.final
end

#encrypt(header, payload) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/sandal/enc/acbc_hs.rb', line 30

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 = derive_encryption_key(content_master_key) 
  iv = cipher.random_iv
  ciphertext = cipher.update(payload) + cipher.final

  secured_parts = [MultiJson.dump(header), encrypted_key, iv, ciphertext]
  secured_input = secured_parts.map { |part| Sandal::Util.base64_encode(part) }.join('.')
  content_integrity_key = derive_integrity_key(content_master_key)
  integrity_value = compute_integrity_value(content_integrity_key, secured_input)

  secured_input << '.' << Sandal::Util.base64_encode(integrity_value)
end