Module: Cybertrain::Crypto
- Defined in:
- cybertrain/crypto.rb
Class Method Summary collapse
-
.random_token(bytes = 32) ⇒ String
SecureRandom.hex, through Crypto.hex (SecureRandom.hex appends a one-character String per digit).
-
.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.
Class Method Details
.random_token(bytes = 32) ⇒ String
SecureRandom.hex, through Crypto.hex (SecureRandom.hex appends a one-character String per digit).
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.)
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 |