Module: DEVp2p::Crypto

Extended by:
Crypto
Included in:
Crypto
Defined in:
lib/devp2p/crypto.rb,
lib/devp2p/crypto/ecc_x.rb,
lib/devp2p/crypto/ecies.rb

Defined Under Namespace

Classes: ECCx, ECIES

Instance Method Summary collapse

Instance Method Details

#ecdsa_recover(msghash, sig) ⇒ Object

Raises:

  • (ArgumentError)


43
44
45
46
47
48
49
50
51
# File 'lib/devp2p/crypto.rb', line 43

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) ⇒ Object

Raises:

  • (ArgumentError)


35
36
37
38
39
40
41
# File 'lib/devp2p/crypto.rb', line 35

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) ⇒ Object Also known as: verify

Raises:

  • (ArgumentError)


53
54
55
56
57
58
59
60
61
# File 'lib/devp2p/crypto.rb', line 53

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

#encrypt(data, raw_pubkey) ⇒ Object

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

Raises:

  • (ArgumentError)


67
68
69
70
# File 'lib/devp2p/crypto.rb', line 67

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) ⇒ Object



31
32
33
# File 'lib/devp2p/crypto.rb', line 31

def hmac_sha256(key, msg)
  OpenSSL::HMAC.digest 'sha256', key, msg
end

#keccak256(x) ⇒ Object



27
28
29
# File 'lib/devp2p/crypto.rb', line 27

def keccak256(x)
  Digest::SHA3.new(256).digest(x)
end

#mk_privkey(seed) ⇒ Object



14
15
16
# File 'lib/devp2p/crypto.rb', line 14

def mk_privkey(seed)
  Crypto.keccak256 seed
end

#privtopub(privkey) ⇒ Object

Raises:



18
19
20
21
22
23
24
25
# File 'lib/devp2p/crypto.rb', line 18

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