Secret: check multiple uses

This commit is contained in:
Didactic Drunk 2022-05-20 13:02:16 -07:00
parent 1c5a444633
commit 054503db7e
2 changed files with 35 additions and 6 deletions

View File

@ -8,8 +8,24 @@ test_secret_class Crypto::Secret::Bidet
describe Crypto::Secret do describe Crypto::Secret do
it ".for" do it ".for" do
[:kgk, :key, :data, :not].each do |sym| [:kgk, :key, :data, :not].each do |sym|
secret = Crypto::Secret.for sym, 2 secret = Crypto::Secret.for 2, sym
secret.bytesize.should eq 2 secret.bytesize.should eq 2
end end
end end
it ".for fallback" do
secret = Crypto::Secret.for 2, :a, :b, :not
secret.bytesize.should eq 2
end
it ".for missing" do
expect_raises(KeyError) do
Crypto::Secret.for 2, :a
end
end
it ".random" do
secret = Crypto::Secret.random 2, :a, :b, :not
secret.bytesize.should eq 2
end
end end

View File

@ -31,7 +31,9 @@ abstract class Crypto::Secret
Readwrite Readwrite
end end
macro inherited
extend ClassMethods extend ClassMethods
end
def self.new(size : Int32) def self.new(size : Int32)
raise NotImplementedError.new("workaround for lack of `abstract def self.new`") raise NotImplementedError.new("workaround for lack of `abstract def self.new`")
@ -41,12 +43,23 @@ abstract class Crypto::Secret
secret secret
end end
def self.for(use : Symbol, size : Int32) : Crypto::Secret
for(use).new(size) def self.for(size : Int32, *uses) : Crypto::Secret
for(*uses).new(size)
end end
def self.for(use : Symbol) : Crypto::Secret.class def self.for(size : Int32, secret : Crypto::Secret) : Crypto::Secret
Config::USES[use] raise ArgumentError.new("") unless size == secret.bytesize
secret
end
def self.for(*uses) : Crypto::Secret.class
uses.each do |use|
if klass = Config::USES[use]?
return klass
end
end
raise KeyError.new("missing #{uses}, have #{Config::USES.keys}")
end end
# For debugging. Leaks the secret # For debugging. Leaks the secret