Skip to content

Commit

Permalink
Support for Blake2b in keyed mode
Browse files Browse the repository at this point in the history
With test vectors taken from the C# implementation

This begins to show the ugliness of the existing encoding API leaking out. It's
probably more important to support the key parameter.

Blake2b supports more options than just a key (e.g. a salt for randomized
hashing, personalization string, fanout, etc) so it might make sense for
the second parameter to be an options hash.
  • Loading branch information
tarcieri committed May 28, 2013
1 parent 115ca24 commit b61048f
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
6 changes: 4 additions & 2 deletions lib/rbnacl/hash.rb
Expand Up @@ -57,9 +57,11 @@ def self.sha512(data, encoding = :raw)
# @raise [CryptoError] If the hashing fails for some reason.
#
# @return [String] The blake2b hash as raw bytes (Or encoded as per the second argument)
def self.blake2b(data, encoding = :raw)
def self.blake2b(data, key = nil, encoding = :raw)
hash = Util.zeros(NaCl::BLAKE2B_OUTBYTES)
NaCl.crypto_hash_blake2b(hash, NaCl::BLAKE2B_OUTBYTES, data, data.bytesize, nil, 0) || raise(CryptoError, "Hashing failed!")
raise LengthError, "key too long" if key && key.bytesize > NaCl::BLAKE2B_KEYBYTES

NaCl.crypto_hash_blake2b(hash, NaCl::BLAKE2B_OUTBYTES, data, data.bytesize, key, key ? key.bytesize : 0) || raise(CryptoError, "Hashing failed!")
Encoder[encoding].encode(hash)
end
else
Expand Down
13 changes: 13 additions & 0 deletions spec/rbnacl/hash_spec.rb
Expand Up @@ -73,6 +73,19 @@
it "calculates the correct hash for an empty string" do
Crypto::Hash.blake2b("").should eq empty_string_hash
end

context "keyed" do
let(:reference_string_hex) { "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfe" }
let(:reference_string) { hex2bytes reference_string_hex }
let(:reference_string_hash_hex) { "142709d62e28fcccd0af97fad0f8465b971e82201dc51070faa0372aa43e92484be1c1e73ba10906d5d1853db6a4106e0a7bf9800d373d6dee2d46d62ef2a461" }
let(:reference_string_hash) { hex2bytes reference_string_hash_hex }
let(:reference_key_hex) { "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f" }
let(:reference_key) { hex2bytes reference_key_hex }

it "calculates keyed hashes correctly" do
Crypto::Hash.blake2b(reference_string, reference_key).should eq reference_string_hash
end
end
end
end
end

0 comments on commit b61048f

Please sign in to comment.