跳至内容 跳至搜索

用于生成和推导出随机密钥的工具。

方法
D
G
N

属性

[R] hash_digest_class

类公共方法

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

# 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

实例公共方法

derive_key_from(password, length: key_length)

从给定的密码推导出密钥。密钥的字节大小为 :length(默认情况下为配置的 Cipher 长度)。

生成的密钥将使用 ActiveRecord::Encryption.key_derivation_salt 的值进行加盐。

# 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)

返回一个十六进制格式的随机密钥。密钥的字节大小为 :length(默认情况下为配置的 Cipher 长度)。

十六进制格式便于将密钥表示为可打印的文本。为了最大限度地利用字符空间,最好包含不可打印的字符。十六进制格式确保生成的密钥可以用纯文本表示。

要将字符串转换回原始长度。

[ value ].pack("H*")
# 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)

返回一个随机密钥。密钥的字节大小为 :length(默认情况下为配置的 Cipher 长度)。

# File activerecord/lib/active_record/encryption/key_generator.rb, line 16
def generate_random_key(length: key_length)
  SecureRandom.random_bytes(length)
end