Class: DiasporaFederation::Salmon::AES

Inherits:
Object
  • Object
show all
Defined in:
lib/diaspora_federation/salmon/aes.rb

Overview

Class for AES encryption and decryption

Constant Summary collapse

CIPHER =

OpenSSL aes cipher definition

"AES-256-CBC"

Class Method Summary collapse

Class Method Details

.decrypt(ciphertext, key, iv) ⇒ String

Decrypts the given ciphertext with an AES cipher defined by the given key and iv. ciphertext is expected to be base64 encoded

Parameters:

  • ciphertext (String)

    input data

  • key (String)

    AES key

  • iv (String)

    AES initialization vector

Returns:

  • (String)

    decrypted plain message

Raises:

  • (ArgumentError)

    if any of the arguments is missing or not the correct type



46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/diaspora_federation/salmon/aes.rb', line 46

def self.decrypt(ciphertext, key, iv) # rubocop:disable Naming/MethodParameterName
  raise ArgumentError unless ciphertext.instance_of?(String) &&
                             key.instance_of?(String) &&
                             iv.instance_of?(String)

  decipher = OpenSSL::Cipher.new(CIPHER)
  decipher.decrypt
  decipher.key = key
  decipher.iv = iv

  decipher.update(Base64.decode64(ciphertext)) + decipher.final
end

.encrypt(data, key, iv) ⇒ String

Encrypts the given data with an AES cipher defined by the given key and iv and returns the resulting ciphertext base64 strict_encoded.

Parameters:

  • data (String)

    plain input

  • key (String)

    AES key

  • iv (String)

    AES initialization vector

Returns:

  • (String)

    base64 encoded ciphertext

Raises:

  • (ArgumentError)

    if any of the arguments is missing or not the correct type



24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/diaspora_federation/salmon/aes.rb', line 24

def self.encrypt(data, key, iv) # rubocop:disable Naming/MethodParameterName
  raise ArgumentError unless data.instance_of?(String) &&
                             key.instance_of?(String) &&
                             iv.instance_of?(String)

  cipher = OpenSSL::Cipher.new(CIPHER)
  cipher.encrypt
  cipher.key = key
  cipher.iv = iv

  ciphertext = cipher.update(data) + cipher.final

  Base64.strict_encode64(ciphertext)
end

.generate_key_and_ivHash

Generates a random AES key and initialization vector

Returns:

  • (Hash)

    { key: “…”, iv: “…” }



12
13
14
15
# File 'lib/diaspora_federation/salmon/aes.rb', line 12

def self.generate_key_and_iv
  cipher = OpenSSL::Cipher.new(CIPHER)
  {key: cipher.random_key, iv: cipher.random_iv}
end