/vendor/bundle/jruby/2.1/gems/rbnacl-3.0.1/lib/rbnacl/hash/blake2b.rb

https://github.com/delowong/logstash · Ruby · 64 lines · 34 code · 6 blank · 24 comment · 6 complexity · 953c9c8e79163097bdfbdb1f77781983 MD5 · raw file

  1. # encoding: binary
  2. module RbNaCl
  3. module Hash
  4. # The Blake2b hash function
  5. #
  6. # Blake2b is based on Blake, a SHA3 finalist which was snubbed in favor of
  7. # Keccak, a much slower hash function but one sufficiently different from
  8. # SHA2 to let the SHA3 judges panel sleep easy. Back in the real world,
  9. # it'd be great if we can calculate hashes quickly if possible.
  10. #
  11. # Blake2b provides for up to 64-bit digests and also supports a keyed mode
  12. # similar to HMAC
  13. class Blake2b
  14. extend Sodium
  15. sodium_type :generichash
  16. sodium_primitive :blake2b
  17. sodium_constant :BYTES_MIN
  18. sodium_constant :BYTES_MAX
  19. sodium_constant :KEYBYTES_MIN
  20. sodium_constant :KEYBYTES_MAX
  21. sodium_function :generichash_blake2b,
  22. :crypto_generichash_blake2b,
  23. [:pointer, :ulong_long, :pointer, :ulong_long, :pointer, :ulong_long]
  24. # Create a new Blake2b hash object
  25. #
  26. # @param [Hash] opts Blake2b configuration
  27. # @option opts [String] :key for Blake2b keyed mode
  28. # @option opts [Integer] :digest_size size of output digest in bytes
  29. #
  30. # @raise [RbNaCl::LengthError] Invalid length specified for one or more options
  31. #
  32. # @return [RbNaCl::Hash::Blake2b] A Blake2b hasher object
  33. def initialize(opts = {})
  34. @key = opts.fetch(:key, nil)
  35. if @key
  36. @key_size = @key.bytesize
  37. raise LengthError, "key too short" if @key_size < KEYBYTES_MIN
  38. raise LengthError, "key too long" if @key_size > KEYBYTES_MAX
  39. else
  40. @key_size = 0
  41. end
  42. @digest_size = opts.fetch(:digest_size, BYTES_MAX)
  43. raise LengthError, "digest size too short" if @digest_size < BYTES_MIN
  44. raise LengthError, "digest size too long" if @digest_size > BYTES_MAX
  45. end
  46. # Calculate a Blake2b digest
  47. #
  48. # @param [String] message Message to be hashed
  49. #
  50. # @return [String] Blake2b digest of the string as raw bytes
  51. def digest(message)
  52. digest = Util.zeros(@digest_size)
  53. self.class.generichash_blake2b(digest, @digest_size, message, message.bytesize, @key, @key_size) || raise(CryptoError, "Hashing failed!")
  54. digest
  55. end
  56. end
  57. end
  58. end