Module: Cybertrain::Crypto

Defined in:
cybertrain/crypto.rb

Class Method Summary collapse

Class Method Details

.random_token(bytes = 32) ⇒ String

SecureRandom.hex, through Crypto.hex (SecureRandom.hex appends a one-character String per digit).

Examples:

Cybertrain::Crypto.random_token(16)   # => "3f9c..." (32 hex digits)

Parameters:

  • bytes (Integer) (defaults to: 32) —

    how many random bytes

Returns:

  • (String) —

    twice as many lowercase hex digits



67
68
69
# File 'cybertrain/crypto.rb', line 67

def self.random_token(bytes = 32)
  Crypto.hex(SecureRandom.random_bytes(bytes))
end

.secure_compare(a, b) ⇒ Boolean

Constant-time byte comparison: every byte pair is examined regardless of an early mismatch, so the running time does not leak how much of a signature or token was guessed correctly. (Strings of different lengths return false at once: the length is not the secret.)

Examples:

Cybertrain::Crypto.secure_compare(params[:token].to_s, SetupController.setup_token)

Parameters:

  • a (String)
  • b (String)

Returns:

  • (Boolean) —

    whether the two hold the same bytes



46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'cybertrain/crypto.rb', line 46

def self.secure_compare(a, b)
  return false if a.bytesize != b.bytesize

  a_bytes = a.bytes
  b_bytes = b.bytes
  diff = 0
  i = 0
  while i < a_bytes.length
    diff |= (a_bytes[i] ^ b_bytes[i])
    i += 1
  end
  diff == 0
end