Class: Sekret::BodyEncryption

Inherits:
Object
  • Object
show all
Defined in:
lib/sekret/body_encryption.rb

Overview

Performs the AES encryption on the message body

Author:

  • Maddie Schipper

Since:

  • 1.0.0

Defined Under Namespace

Classes: Result

Constant Summary collapse

ALGORITHM =

The algorithm used for encryption/decryption

Since:

  • 1.0.0

'AES-256-CBC'.freeze

Class Method Summary collapse

Class Method Details

.decrypt(header, encrypted) ⇒ String

Decrypt the payload

Parameters:

  • header (Header)

    The header that contains the key, iv, & checksum

  • encrypted (String)

    The encrypted content

Returns:

  • (String)

    The un-encrypted message

Since:

  • 1.0.0



56
57
58
59
60
61
62
63
64
65
# File 'lib/sekret/body_encryption.rb', line 56

def decrypt(header, encrypted)
  validate_checksum!(header.authenticity, encrypted)
  aes = OpenSSL::Cipher.new(ALGORITHM)
  aes.decrypt
  aes.key = header.key
  aes.iv = header.iv
  plaintext = aes.update(encrypted)
  plaintext << aes.final
  plaintext
end

.encrypt(plaintext) ⇒ Result

Encrypt a payload using a random key and iv

Parameters:

  • plaintext (String)

    The payload to encrypt

Returns:

Since:

  • 1.0.0



36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/sekret/body_encryption.rb', line 36

def encrypt(plaintext)
  key = OpenSSL::Cipher.new(ALGORITHM).random_key
  iv = OpenSSL::Cipher.new(ALGORITHM).random_iv
  aes = OpenSSL::Cipher.new(ALGORITHM)
  aes.encrypt
  aes.key = key
  aes.iv = iv
  cipher = aes.update(plaintext)
  cipher << aes.final
  digest = generate_digest(cipher)
  Result.new(key, iv, digest, cipher)
end