Class: AesBridge::RandomGenerator
- Inherits:
-
Object
- Object
- AesBridge::RandomGenerator
- Defined in:
- lib/aes_bridge/common.rb
Overview
A class for generating cryptographically secure random bytes using a nonce.
Constant Summary collapse
- @@nonce =
Class variable to store the nonce.
nil- @@nonce_mutex =
Mutex for safe access to nonce in a multi-threaded environment.
Mutex.new
Class Method Summary collapse
-
.update_nonce ⇒ Object
Updates the nonce.
Instance Method Summary collapse
-
#generate_random_bytes(size) ⇒ String
Generates cryptographically secure random bytes.
Class Method Details
.update_nonce ⇒ Object
Updates the nonce
26 27 28 29 30 31 32 33 34 35 |
# File 'lib/aes_bridge/common.rb', line 26 def self.update_nonce @@nonce_mutex.synchronize do if @@nonce.nil? # Generate a random starting value for the nonce. nonce = OpenSSL::Random.random_bytes(8) @@nonce = nonce.unpack('Q>').first end @@nonce += 1 end end |
Instance Method Details
#generate_random_bytes(size) ⇒ String
Generates cryptographically secure random bytes.
41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/aes_bridge/common.rb', line 41 def generate_random_bytes(size) self.class.update_nonce nonce_value = nil @@nonce_mutex.synchronize do nonce_value = @@nonce end nonce_bytes = [nonce_value].pack('Q>') # Generate random bytes before and after the nonce to increase entropy. data = OpenSSL::Random.random_bytes(13) + nonce_bytes + OpenSSL::Random.random_bytes(13) OpenSSL::Digest::SHA256.digest(data)[0, size] end |