module DEVp2p::Crypto

Public Instance Methods

ecdsa_recover(msghash, sig) click to toggle source
# File lib/devp2p/crypto.rb, line 42
def ecdsa_recover(msghash, sig)
  raise ArgumentError, 'msghash length must be 32' unless msghash.size == 32
  raise ArgumentError, 'signature length must be 65' unless sig.size == 65

  pub = Secp256k1::PublicKey.new flags: Secp256k1::ALL_FLAGS
  recsig = pub.ecdsa_recoverable_deserialize sig[0,64], sig[64].ord
  pub.public_key = pub.ecdsa_recover msghash, recsig, raw: true
  pub.serialize(compressed: false)[1..-1]
end
ecdsa_sign(msghash, privkey) click to toggle source
# File lib/devp2p/crypto.rb, line 34
def ecdsa_sign(msghash, privkey)
  raise ArgumentError, 'msghash length must be 32' unless msghash.size == 32

  priv = Secp256k1::PrivateKey.new privkey: privkey, raw: true
  sig = priv.ecdsa_recoverable_serialize priv.ecdsa_sign_recoverable(msghash, raw: true)
  "#{sig[0]}#{sig[1].chr}"
end
ecdsa_verify(pubkey, sig, msg) click to toggle source
# File lib/devp2p/crypto.rb, line 52
def ecdsa_verify(pubkey, sig, msg)
  raise ArgumentError, 'invalid signature length' unless sig.size == 65
  raise ArgumentError, 'invalid pubkey length' unless pubkey.size == 64

  pub = Secp256k1::PublicKey.new pubkey: "\x04#{pubkey}", raw: true
  raw_sig = pub.ecdsa_recoverable_convert pub.ecdsa_recoverable_deserialize(sig[0,64], sig[64].ord)

  pub.ecdsa_verify msg, raw_sig, raw: true
end
Also aliased as: verify
encrypt(data, raw_pubkey) click to toggle source

Encrypt data with ECIES method using the public key of the recipient.

# File lib/devp2p/crypto.rb, line 66
def encrypt(data, raw_pubkey)
  raise ArgumentError, "invalid pubkey of length #{raw_pubkey.size}" unless raw_pubkey.size == 64
  Crypto::ECIES.encrypt data, raw_pubkey
end
hmac_sha256(key, msg) click to toggle source
# File lib/devp2p/crypto.rb, line 30
def hmac_sha256(key, msg)
  OpenSSL::HMAC.digest 'sha256', key, msg
end
keccak256(x) click to toggle source
# File lib/devp2p/crypto.rb, line 26
def keccak256(x)
  Digest::SHA3.new(256).digest(x)
end
mk_privkey(seed) click to toggle source
# File lib/devp2p/crypto.rb, line 13
def mk_privkey(seed)
  Crypto.keccak256 seed
end
privtopub(privkey) click to toggle source
# File lib/devp2p/crypto.rb, line 17
def privtopub(privkey)
  priv = Secp256k1::PrivateKey.new privkey: privkey, raw: true

  pub = priv.pubkey.serialize(compressed: false)
  raise InvalidKeyError, 'invalid pubkey' unless pub.size == 65 && pub[0] == "\x04"

  pub[1,64]
end
verify(pubkey, sig, msg)
Alias for: ecdsa_verify