Skip to content

Commit

Permalink
Merge 753ab67 into 907bf0c
Browse files Browse the repository at this point in the history
  • Loading branch information
tarcieri committed May 26, 2013
2 parents 907bf0c + 753ab67 commit 559d22c
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
16 changes: 16 additions & 0 deletions lib/rbnacl/hash.rb
Original file line number Diff line number Diff line change
Expand Up @@ -44,5 +44,21 @@ def self.sha512(data, encoding = :raw)
NaCl.crypto_hash_sha512(hash, data, data.bytesize) || raise(CryptoError, "Hashing failed!")
Encoder[encoding].encode(hash)
end

# Returns the Blake2b hash of the given data
#
# There's no streaming done, just pass in the data and be done with it.
#
# @param [String] data The data, as a collection of bytes
# @param [#to_sym] encoding Encoding of the returned hash.
#
# @raise [CryptoError] If the hashing fails for some reason.
#
# @return [String] The SHA-512 hash as raw bytes (Or encoded as per the second argument)
def self.blake2b(data, 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!")
Encoder[encoding].encode(hash)
end
end
end
6 changes: 6 additions & 0 deletions lib/rbnacl/nacl.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,12 @@ def self.#{name}(*args)
:crypto_hash_sha512_ref,
[:pointer, :pointer, :long_long]

BLAKE2B_OUTBYTES = 64
BLAKE2B_KEYBYTES = 64
wrap_nacl_function :crypto_hash_blake2b,
:crypto_generichash_blake2b,
[:pointer, :size_t, :pointer, :long_long, :pointer, :size_t]

CURVE25519_XSALSA20_POLY1305_PUBLICKEY_BYTES = 32
PUBLICKEYBYTES = CURVE25519_XSALSA20_POLY1305_PUBLICKEY_BYTES
CURVE25519_XSALSA20_POLY1305_SECRETKEY_BYTES = 32
Expand Down
16 changes: 16 additions & 0 deletions spec/rbnacl/hash_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -57,4 +57,20 @@
expect { Crypto::Hash.sha512("\0") }.to_not raise_error(/ArgumentError: string contains null byte/)
end
end

context "blake2b" do
let(:reference_string) { 'The quick brown fox jumps over the lazy dog' }
let(:reference_string_hash_hex) { 'a8add4bdddfd93e4877d2746e62817b116364a1fa7bc148d95090bc7333b3673f82401cf7aa2e4cb1ecd90296e3f14cb5413f8ed77be73045b13914cdcd6a918' }
let(:empty_string_hash_hex) { '786a02f742015903c6c6fd852552d272912f4740e15847618a86e217f71f5419d25e1031afee585313896444934eb04b903a685b1448b755d56f701afe9be2ce' }
let(:reference_string_hash) { [reference_string_hash_hex].pack('H*') }
let(:empty_string_hash) { [empty_string_hash].pack('H*') }

it "calculates the correct hash for a reference string" do
Crypto::Hash.blake2b(reference_string).should eq reference_string_hash
end

it "calculates the correct hash for an empty string" do
Crypto::Hash.blake2b("").should eq empty_string_hash
end
end
end

0 comments on commit 559d22c

Please sign in to comment.