Module: ECDSA::Format::IntegerOctetString

Defined in:
lib/ecdsa/format/integer_octet_string.rb

Overview

This module provides methods for converting integers to big endian octet strings. The conversions are defined in these sections of [SEC1](www.secg.org/collateral/sec1_final.pdf):

  • Section 2.3.7: Integer-to-OctetString Conversion

  • Section 2.3.8: OctetString-to-Integer Conversion

We use Ruby integers to represent bit strings, so this module can also be thought of as implementing these sections of SEC1:

  • Section 2.3.1: BitString-to-OctetString Conversion

  • Section 2.3.2: OctetString-to-BitString Conversion

Class Method Summary collapse

Class Method Details

.decode(string) ⇒ Integer

Parameters:

  • string (String)

Returns:

  • (Integer)


30
31
32
# File 'lib/ecdsa/format/integer_octet_string.rb', line 30

def self.decode(string)
  string.bytes.reduce { |n, b| (n << 8) + b }
end

.encode(integer, length) ⇒ String

Parameters:

  • integer (Integer)

    The integer to encode.

  • length (Integer)

    The number of bytes desired in the output string.

Returns:

  • (String)

Raises:

  • (ArgumentError)


19
20
21
22
23
24
25
26
# File 'lib/ecdsa/format/integer_octet_string.rb', line 19

def self.encode(integer, length)
  raise ArgumentError, 'Integer to encode is negative.' if integer < 0
  raise ArgumentError, 'Integer to encode is too large.' if integer >= (1 << (8 * length))

  (length - 1).downto(0).map do |i|
    (integer >> (8 * i)) & 0xFF
  end.pack('C*')
end