.random Allow specifying the Random source

This commit is contained in:
Didactic Drunk 2022-05-22 22:58:26 -07:00
parent 321db6f397
commit a2040b54e2
2 changed files with 8 additions and 6 deletions

View File

@ -207,7 +207,7 @@ end
**Only intended for use by crypto library authors** **Only intended for use by crypto library authors**
``` ```crystal
class MySecret < Crypto::Secret class MySecret < Crypto::Secret
# Choose one # Choose one
include Crypto::Secret::Stateless include Crypto::Secret::Stateless

View File

@ -40,11 +40,13 @@ abstract class Crypto::Secret
raise NotImplementedError.new("workaround for lack of `abstract def self.new`") raise NotImplementedError.new("workaround for lack of `abstract def self.new`")
end end
def self.random(size : Int32, *uses : Symbol) : Crypto::Secret # def self.random(size : Int32, *uses : Symbol, *, random = Random::Secure) : Crypto::Secret
for(size, *uses).random def self.random(size : Int32, *uses : Symbol, **options) : Crypto::Secret
rand = options[:random]? || Random::Secure
for(size, *uses).random(random: rand)
end end
def self.for(size : Int32, *uses) : Crypto::Secret def self.for(size : Int32, *uses : Symbol) : Crypto::Secret
for(*uses).new(size) for(*uses).new(size)
end end
@ -98,9 +100,9 @@ abstract class Crypto::Secret
end end
# Fills `Secret` with secure random data # Fills `Secret` with secure random data
def random : self def random(random = Random::Secure) : self
readwrite do |slice| readwrite do |slice|
Random::Secure.random_bytes slice random.random_bytes slice
end end
self self
end end