PageRenderTime 14ms CodeModel.GetById 7ms app.highlight 5ms RepoModel.GetById 1ms app.codeStats 0ms

/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
 2module 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
16      sodium_type      :generichash
17      sodium_primitive :blake2b
18      sodium_constant  :BYTES_MIN
19      sodium_constant  :BYTES_MAX
20      sodium_constant  :KEYBYTES_MIN
21      sodium_constant  :KEYBYTES_MAX
22
23      sodium_function  :generichash_blake2b,
24                       :crypto_generichash_blake2b,
25                       [:pointer, :ulong_long, :pointer, :ulong_long, :pointer, :ulong_long]
26
27      # Create a new Blake2b hash object
28      #
29      # @param [Hash] opts Blake2b configuration
30      # @option opts [String]  :key for Blake2b keyed mode
31      # @option opts [Integer] :digest_size size of output digest in bytes
32      #
33      # @raise [RbNaCl::LengthError] Invalid length specified for one or more options
34      #
35      # @return [RbNaCl::Hash::Blake2b] A Blake2b hasher object
36      def initialize(opts = {})
37        @key = opts.fetch(:key, nil)
38
39        if @key
40          @key_size = @key.bytesize
41          raise LengthError, "key too short" if @key_size < KEYBYTES_MIN
42          raise LengthError, "key too long"  if @key_size > KEYBYTES_MAX
43        else
44          @key_size = 0
45        end
46
47        @digest_size = opts.fetch(:digest_size, BYTES_MAX)
48        raise LengthError, "digest size too short" if @digest_size < BYTES_MIN
49        raise LengthError, "digest size too long"  if @digest_size > BYTES_MAX
50      end
51
52      # Calculate a Blake2b digest
53      #
54      # @param [String] message Message to be hashed
55      #
56      # @return [String] Blake2b digest of the string as raw bytes
57      def digest(message)
58        digest = Util.zeros(@digest_size)
59        self.class.generichash_blake2b(digest, @digest_size, message, message.bytesize, @key, @key_size) || raise(CryptoError, "Hashing failed!")
60        digest
61      end
62    end
63  end
64end