Class: IOTA::Crypto::Kerl

Inherits:
Object
  • Object
show all
Defined in:
lib/iota/crypto/kerl.rb

Constant Summary collapse

BIT_HASH_LENGTH =
384
HASH_LENGTH =
Curl::HASH_LENGTH

Instance Method Summary collapse

Constructor Details

#initializeKerl

Returns a new instance of Kerl.



7
8
9
# File 'lib/iota/crypto/kerl.rb', line 7

def initialize
  reset
end

Instance Method Details

#absorb(trits, offset = 0, length = nil) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/iota/crypto/kerl.rb', line 21

def absorb(trits, offset = 0, length = nil)
  pad = trits.length % HASH_LENGTH != 0 ? trits.length % HASH_LENGTH : HASH_LENGTH
  trits.concat([0] * (HASH_LENGTH - pad))

  length = trits.length if length.nil?

  if length % HASH_LENGTH != 0 || length == 0
    raise StandardError,  "Illegal length provided"
  end

  while offset < length
    limit = [offset + HASH_LENGTH, length].min

    # If we're copying over a full chunk, zero last trit
    trits[limit - 1] = 0 if limit - offset == HASH_LENGTH

    signed_bytes = Converter.convertToBytes(trits[offset...limit])

    # Convert signed bytes into their equivalent unsigned representation
    # In order to use Python's built-in bytes type
    unsigned_bytes = signed_bytes.map{ |b| Converter.convertSign(b) }.pack('c*').force_encoding('UTF-8')

    @hasher.update(unsigned_bytes)

    offset += HASH_LENGTH
  end
end

#resetObject



11
12
13
14
15
16
17
18
19
# File 'lib/iota/crypto/kerl.rb', line 11

def reset
  unless RUBY_PLATFORM =~ /java/
    require 'digest/sha3'
    @hasher = Digest::SHA3.new(BIT_HASH_LENGTH)
  else
    require "iota/crypto/sha3_ruby"
    @hasher = Digest::RubySHA3.new(BIT_HASH_LENGTH)
  end
end

#squeeze(trits, offset = 0, length = nil) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/iota/crypto/kerl.rb', line 49

def squeeze(trits, offset = 0, length = nil)
  pad = trits.length % HASH_LENGTH != 0 ? trits.length % HASH_LENGTH : HASH_LENGTH
  trits.concat([0] * (HASH_LENGTH - pad))

  length = trits.length > 0 ? trits.length : HASH_LENGTH if length.nil?

  if length % HASH_LENGTH != 0 || length == 0
    raise StandardError,  "Illegal length provided"
  end

  while offset < length
    unsigned_hash =  @hasher.digest

    signed_hash = unsigned_hash.bytes.map { |b| Converter.convertSign(b) }

    trits_from_hash = Converter.convertToTrits(signed_hash)
    trits_from_hash[HASH_LENGTH - 1] = 0

    limit = [HASH_LENGTH, length - offset].min

    trits[offset...offset+limit] = trits_from_hash[0...limit]

    flipped_bytes = unsigned_hash.bytes.map{ |b| Converter.convertSign(~b)}.pack('c*').force_encoding('UTF-8')

    # Reset internal state before feeding back in
    reset
    @hasher.update(flipped_bytes)

    offset += HASH_LENGTH
  end
end