123456789_123456789_123456789_123456789_123456789_

Class: ActiveRecord::Encryption::KeyGenerator

Relationships & Source Files
Inherits: Object
Defined in: activerecord/lib/active_record/encryption/key_generator.rb

Overview

Utility for generating and deriving random keys.

Class Method Summary

Instance Attribute Summary

Instance Method Summary

Constructor Details

.new(hash_digest_class: ActiveRecord::Encryption.config.hash_digest_class) ⇒ KeyGenerator

[ GitHub ]

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

def initialize(hash_digest_class: ActiveRecord::Encryption.config.hash_digest_class)
  @hash_digest_class = hash_digest_class
end

Instance Attribute Details

#hash_digest_class (readonly)

[ GitHub ]

  
# File 'activerecord/lib/active_record/encryption/key_generator.rb', line 9

attr_reader :hash_digest_class

Instance Method Details

#derive_key_from(password, length: key_length)

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

[ GitHub ]

  
# File 'activerecord/lib/active_record/encryption/key_generator.rb', line 38

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

#generate_random_hex_key(length: key_length)

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*")
[ GitHub ]

  
# File 'activerecord/lib/active_record/encryption/key_generator.rb', line 30

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

#generate_random_key(length: key_length)

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

[ GitHub ]

  
# File 'activerecord/lib/active_record/encryption/key_generator.rb', line 16

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

#key_derivation_salt (private)

[ GitHub ]

  
# File 'activerecord/lib/active_record/encryption/key_generator.rb', line 44

def key_derivation_salt
  @key_derivation_salt ||= ActiveRecord::Encryption.config.key_derivation_salt
end

#key_length (private)

[ GitHub ]

  
# File 'activerecord/lib/active_record/encryption/key_generator.rb', line 48

def key_length
  @key_length ||= ActiveRecord::Encryption.cipher.key_length
end