Class: Bitcoin::BIP324::Poly1305

Inherits:
Object
  • Object
show all
Defined in:
lib/bitcoin/bip324/fs_chacha_poly1305.rb

Overview

Class representing a running poly1305 computation.

Constant Summary collapse

MODULUS =
2**130 - 5
TAG_LEN =
16

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key) ⇒ Poly1305

Constructor



15
16
17
18
19
# File 'lib/bitcoin/bip324/fs_chacha_poly1305.rb', line 15

def initialize(key)
  @r = key[0...16].reverse.bti & 0xffffffc0ffffffc0ffffffc0fffffff
  @s = key[16..-1].reverse.bti
  @acc = 0
end

Instance Attribute Details

#accObject

Returns the value of attribute acc.



11
12
13
# File 'lib/bitcoin/bip324/fs_chacha_poly1305.rb', line 11

def acc
  @acc
end

#rObject (readonly)

Returns the value of attribute r.



9
10
11
# File 'lib/bitcoin/bip324/fs_chacha_poly1305.rb', line 9

def r
  @r
end

#sObject (readonly)

Returns the value of attribute s.



10
11
12
# File 'lib/bitcoin/bip324/fs_chacha_poly1305.rb', line 10

def s
  @s
end

Instance Method Details

#add(msg, length: nil, padding: false) ⇒ Poly1305

Add a message of any length. Input so far must be a multiple of 16 bytes.

Parameters:

  • msg (String)

    A message with binary format.

Returns:



24
25
26
27
28
29
30
31
32
# File 'lib/bitcoin/bip324/fs_chacha_poly1305.rb', line 24

def add(msg, length: nil, padding: false)
  len = length ? length : msg.bytesize
  ((len + 15) / 16).times do |i|
    chunk = msg[(i * 16)...(i * 16 + [16, len - i * 16].min)]
    val = chunk.reverse.bti + 256**(padding ? 16 : chunk.bytesize)
    self.acc = r * (acc + val) % MODULUS
  end
  self
end

#tagObject

Compute the poly1305 tag.

Returns:

  • Poly1305 tag wit binary format.



36
37
38
# File 'lib/bitcoin/bip324/fs_chacha_poly1305.rb', line 36

def tag
  ECDSA::Format::IntegerOctetString.encode((acc + s) & 0xffffffffffffffffffffffffffffffff, TAG_LEN).reverse
end