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".freeze

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

Raises:

  • (ArgumentError)

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



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

def self.decrypt(ciphertext, key, iv) # rubocop:disable Naming/UncommunicativeMethodParamName
  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.

Raises:

  • (ArgumentError)

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



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

def self.encrypt(data, key, iv) # rubocop:disable Naming/UncommunicativeMethodParamName
  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



10
11
12
13
# File 'lib/diaspora_federation/salmon/aes.rb', line 10

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