Class: Noise::Functions::Hash::Blake2sDigester

Inherits:
Object
  • Object
show all
Defined in:
lib/noise/functions/hash/blake2s.rb

Defined Under Namespace

Classes: Context

Constant Summary collapse

IV =
[0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19].freeze
SIGMA =
[
  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
  [14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3],
  [11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4],
  [7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8],
  [9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13],
  [2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9],
  [12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11],
  [13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10],
  [6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5],
  [10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0]
].freeze

Instance Method Summary collapse

Constructor Details

#initialize(key: '') ⇒ Blake2sDigester

Returns a new instance of Blake2sDigester.



44
45
46
47
# File 'lib/noise/functions/hash/blake2s.rb', line 44

def initialize(key: '')
  @key = key
  @ctx = init(Blake2s::HASHLEN, @key.unpack('C*'))
end

Instance Method Details

#digestObject



54
55
56
57
58
# File 'lib/noise/functions/hash/blake2s.rb', line 54

def digest
  out = []
  final(@ctx, out)
  out.pack('C*')
end

#final(ctx, out) ⇒ Object



89
90
91
92
93
94
95
96
97
98
99
# File 'lib/noise/functions/hash/blake2s.rb', line 89

def final(ctx, out)
  ctx.t += ctx.c
  while ctx.c < Blake2s::BLOCKLEN
    ctx.b[ctx.c] = 0
    ctx.c += 1
  end
  compress(ctx, true)
  ctx.out_len.times do |i|
    out << ((ctx.h[i >> 2] >> (8 * (i & 3))) & 0xff)
  end
end

#init(out_len, key) ⇒ Object

Returns context.

Returns:

  • context

Raises:

  • (ArgumentError)


61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/noise/functions/hash/blake2s.rb', line 61

def init(out_len, key)
  raise ArgumentError if out_len.zero? || out_len > 32
  h = IV.dup
  h[0] ^= 0x01010000 ^ (key.size << 8) ^ out_len
  t = 0
  c = 0
  b = Array.new(Blake2s::BLOCKLEN).fill(0, key.size)
  ctx = Context.new(b, h, t, c, out_len)
  if key.size.positive?
    update_internal(ctx, key)
    ctx.c = 64
  end
  ctx
end

#update(data) ⇒ Object



49
50
51
52
# File 'lib/noise/functions/hash/blake2s.rb', line 49

def update(data)
  update_internal(@ctx, data.unpack('C*'))
  self
end

#update_internal(ctx, input) ⇒ Object



76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/noise/functions/hash/blake2s.rb', line 76

def update_internal(ctx, input)
  input.size.times do |i|
    if ctx.c == Blake2s::BLOCKLEN
      ctx.t += ctx.c
      compress(ctx, false)
      ctx.c = 0
    end

    ctx.b[ctx.c] = input[i]
    ctx.c += 1
  end
end