Module: BitcoinCigs::CryptoHelper

Included in:
BitcoinCigs, Point, PrivateKey, PublicKey, Signature
Defined in:
lib/bitcoin_cigs/crypto_helper.rb

Instance Method Summary collapse

Instance Method Details

#decode58(s) ⇒ Object



23
24
25
# File 'lib/bitcoin_cigs/crypto_helper.rb', line 23

def decode58(s)
  ::BitcoinCigs::Base58.decode(s)
end

#decode64(s) ⇒ Object



15
16
17
# File 'lib/bitcoin_cigs/crypto_helper.rb', line 15

def decode64(s)
  Base64.decode64(s)
end

#decode_hex(s) ⇒ Object



7
8
9
# File 'lib/bitcoin_cigs/crypto_helper.rb', line 7

def decode_hex(s)
  [s].pack('H*')
end

#encode58(s) ⇒ Object



19
20
21
# File 'lib/bitcoin_cigs/crypto_helper.rb', line 19

def encode58(s)
  ::BitcoinCigs::Base58.encode(s)
end

#encode64(s) ⇒ Object



11
12
13
# File 'lib/bitcoin_cigs/crypto_helper.rb', line 11

def encode64(s)
  Base64.strict_encode64(s)
end

#inverse_mod(a, m) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/bitcoin_cigs/crypto_helper.rb', line 27

def inverse_mod(a, m)
  a = a % m if a < 0 || m <= a
  
  c, d = a, m
  
  uc, vc, ud, vd = 1, 0, 0, 1
  
  while c != 0
    q, c, d = d / c, d % c, c
    uc, vc, ud, vd = ud - q*uc, vd - q*vc, uc, vc
  end
  raise ::BitcoinCigs::Error.new unless d == 1
  
  ud > 0 ? ud : ud + m
end

#leftmost_bit(x) ⇒ Object



43
44
45
46
47
48
49
# File 'lib/bitcoin_cigs/crypto_helper.rb', line 43

def leftmost_bit(x)
  raise ::BitcoinCigs::Error.new unless x > 0
  
  result = 1
  result *= 2 while result <= x
  result / 2
end

#ripemd160(d) ⇒ Object



51
52
53
# File 'lib/bitcoin_cigs/crypto_helper.rb', line 51

def ripemd160(d)
  (OpenSSL::Digest::RIPEMD160.new << d).digest
end

#sha256(d) ⇒ Object



55
56
57
# File 'lib/bitcoin_cigs/crypto_helper.rb', line 55

def sha256(d)
  (Digest::SHA256.new << d).digest
end

#sqrt_mod(a, p) ⇒ Object



59
60
61
# File 'lib/bitcoin_cigs/crypto_helper.rb', line 59

def sqrt_mod(a, p)
  a.to_bn.mod_exp((p + 1) / 4, p).to_i
end

#str_to_num(s) ⇒ Object



63
64
65
# File 'lib/bitcoin_cigs/crypto_helper.rb', line 63

def str_to_num(s)
  s.chars.reverse_each.with_index.inject(0) { |acc, (ch, i)| acc + ch.ord * (256 ** i) }
end