Class: Pbkdf2CryptoRecord

Inherits:
CryptoRecord show all
Defined in:
lib/universa_tools/crypto_record.rb

Overview

PBKDF2 KeyRecord. Allow safely using passwords, carrying all necessary information to re-derive key later. Allow using only part of the PBKDF2 derived data as a key, so more than one key could be derived from the same password cryptographically safe and independently.

Constant Summary collapse

HASH_CODES =
[
    "com.icodici.crypto.digest.Sha256", # 0
]

Instance Method Summary collapse

Methods inherited from CryptoRecord

from_packed, #pack, pack_all, unpack_all

Constructor Details

#initialize(params = nil, encrypted_key = nil, salt: 'default_salt', rounds: 500000, key_length: 32, offset: 0, length: 32, hint: nil, hash_code: 0) ⇒ Pbkdf2CryptoRecord

Construct instance using PBKDF2 parameters or serialization parameters.



78
79
80
81
82
83
84
85
86
87
88
# File 'lib/universa_tools/crypto_record.rb', line 78

def initialize(params = nil, encrypted_key = nil, salt: 'default_salt', rounds: 500000, key_length: 32, offset: 0, length: 32, hint: nil, hash_code: 0)
  if params
    @salt_bytes, @rounds, @key_length, @offset, @length, @password_hint, @hash_code = *params
  else
    @salt_bytes, @rounds, @key_length, @offset, @length, @password_hint, @hash_code =
        salt.force_encoding('binary'), rounds, key_length, offset, length, hint, hash_code
  end
  @salt_bytes&.freeze
  @hash = HASH_CODES[@hash_code] or raise ArgumentError, "invalid hash code #{hash_code}"
  super 1, encrypted_key
end

Instance Method Details

#decrypt(password) ⇒ Binary

Decrypt the contained ciphertext deriving a key from a given password

Parameters:

  • password (String)

    to derive key from

Returns:

  • (Binary)

    binary string for the decrypted data



102
103
104
105
# File 'lib/universa_tools/crypto_record.rb', line 102

def decrypt(password)
  @ciphertext or raise IllegalStateError, "missing ciphertext"
  derive_key(password).eta_decrypt(@ciphertext)
end

#encrypt(password, plaintext) ⇒ Pbkdf2CryptoRecord

Encrypt plaintext deriving key from a given password

Returns:



92
93
94
95
96
# File 'lib/universa_tools/crypto_record.rb', line 92

def encrypt(password, plaintext)
  plaintext = plaintext.force_encoding('binary')
  encrypt_with_key(derive_key(password), plaintext)
  self
end

#try_decrypt(password) ⇒ Object



107
108
109
110
111
# File 'lib/universa_tools/crypto_record.rb', line 107

def try_decrypt(password)
  decrypt(password)
rescue Farcall::RemoteError
  nil
end