Class: ActiveRecord::Encryption::KeyGenerator

Inherits:
Object
  • Object
show all
Defined in:
lib/active_record/encryption/key_generator.rb

Overview

Utility for generating and deriving random keys.

Instance Method Summary collapse

Instance Method Details

#derive_key_from(password, length: key_length) ⇒ Object

Derives a key from the given password. The key will have a size in bytes of :length (configured Cipher‘s length by default)

The generated key will be salted with the value of ActiveRecord::Encryption.key_derivation_salt



32
33
34
# File 'lib/active_record/encryption/key_generator.rb', line 32

def derive_key_from(password, length: key_length)
  ActiveSupport::KeyGenerator.new(password).generate_key(ActiveRecord::Encryption.config.key_derivation_salt, length)
end

#generate_random_hex_key(length: key_length) ⇒ Object

Returns a random key in hexadecimal format. The key will have a size in bytes of :length (configured Cipher‘s length by default)

Hexadecimal format is handy for representing keys as printable text. To maximize the space of characters used, it is good practice including not printable characters. Hexadecimal format ensures that generated keys are representable with plain text

To convert back to the original string with the desired length:

[ value ].pack("H*")


24
25
26
# File 'lib/active_record/encryption/key_generator.rb', line 24

def generate_random_hex_key(length: key_length)
  generate_random_key(length: length).unpack("H*")[0]
end

#generate_random_key(length: key_length) ⇒ Object

Returns a random key. The key will have a size in bytes of :length (configured Cipher‘s length by default)



10
11
12
# File 'lib/active_record/encryption/key_generator.rb', line 10

def generate_random_key(length: key_length)
  SecureRandom.random_bytes(length)
end