Module: Ciri::Utils

Defined in:
lib/ciri/utils.rb

Class Method Summary collapse

Class Method Details

.big_endian_decode(input) ⇒ Object


48
49
50
# File 'lib/ciri/utils.rb', line 48

def big_endian_decode(input)
  input.each_byte.reduce(0) {|s, i| s * 256 + i}
end

.big_endian_encode(n, zero = '') ⇒ Object


40
41
42
43
44
45
46
# File 'lib/ciri/utils.rb', line 40

def big_endian_encode(n, zero = '')
  if n == 0
    zero
  else
    big_endian_encode(n / 256) + (n % 256).chr
  end
end

.create_ec_pk(raw_pubkey: nil, raw_privkey: nil) ⇒ Object


60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/ciri/utils.rb', line 60

def create_ec_pk(raw_pubkey: nil, raw_privkey: nil)
  public_key = raw_pubkey && begin
    group = OpenSSL::PKey::EC::Group.new('secp256k1')
    bn = OpenSSL::BN.new(raw_pubkey, 2)
    OpenSSL::PKey::EC::Point.new(group, bn)
  end

  OpenSSL::PKey::EC.new('secp256k1').tap do |key|
    key.public_key = public_key if public_key
    key.private_key = OpenSSL::BN.new(raw_privkey, 2) if raw_privkey
  end
end

.data_to_hex(data) ⇒ Object


56
57
58
# File 'lib/ciri/utils.rb', line 56

def data_to_hex(data)
  data.unpack("H*").first
end

.hex_to_data(hex) ⇒ Object


52
53
54
# File 'lib/ciri/utils.rb', line 52

def hex_to_data(hex)
  [hex].pack("H*")
end

.secret_compare(s1, s2) ⇒ Object


36
37
38
# File 'lib/ciri/utils.rb', line 36

def secret_compare(s1, s2)
  s1.size == s2.size && s1.each_byte.each_with_index.map {|b, i| b ^ s2[i].ord}.reduce(0, :+) == 0
end

.sha3(*data) ⇒ Object


30
31
32
33
34
# File 'lib/ciri/utils.rb', line 30

def sha3(*data)
  s = Digest::SHA3.new(256)
  data.each {|i| s.update(i)}
  s.digest
end