Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
# address = '0xa5df35f30ba0ce878b1061ae086289adff3ba1e0'
address = web3.personal.importRawKey(private_key, "password")
web3.personal.unlockAccount(address, "password")
assert add_0x_prefix(encode_hex(privtoaddr(private_key))) == add_0x_prefix(address)
assert address == '0xa5df35f30ba0ce878b1061ae086289adff3ba1e0'
# the data to be signed
data = b'1234567890abcdefghijklmnopqrstuvwxyz'
# the hash of the data `0x089c33d56ed10bd8b571a0f493cedb28db1ae0f40c6cd266243001528c06eab3`
data_hash = web3.sha3(data, encoding=None)
data_hash_bytes = decode_hex(data_hash)
assert force_bytes(data_hash) == sha3(data)
priv_key = PrivateKey(flags=ALL_FLAGS)
priv_key.set_raw_privkey(private_key)
# sanit check the extract_ecdsa_signer function works as expected.
vector_sig = priv_key.ecdsa_sign_recoverable(data_hash_bytes, raw=True, digest=hashlib.sha3_256)
vector_sig_bytes, rec_id = priv_key.ecdsa_recoverable_serialize(vector_sig)
vector_sig_bytes_full = vector_sig_bytes + force_bytes(chr(rec_id))
vector_address = force_text(extract_ecdsa_signer(data_hash_bytes, vector_sig_bytes_full))
assert vector_address == address
# Now have geth sign some data.
signature_hex = web3.eth.sign(address, data)
signature_bytes = decode_hex(signature_hex)
# geth prefix message before signing
geth_prefix_data = eth_message_prefix_hash(web3, data.decode())
"""
ECDSA
eliptical curve digital signature algorithm
this is where the real hocus pocus lies
all of the ordering, typing, serializing, and digesting
culminates with the message meeting the wif
"""
# 8 bit string representation of private key
p = bytes(PrivateKey(wif))
# create some arbitrary data used by the nonce generation
ndata = secp256k1_ffi.new("const int *ndata")
ndata[0] = 0 # it adds "\0x00", then "\0x00\0x00", etc..
while True: # repeat process until deterministic and cannonical
ndata[0] += 1 # increment the arbitrary nonce
# obtain compiled/binary private key from the wif
privkey = secp256k1_PrivateKey(p, raw=True)
print(it('red',str(privkey)))
print(privkey)
# create a new recoverable 65 byte ECDSA signature
sig = secp256k1_ffi.new(
"secp256k1_ecdsa_recoverable_signature *"
)
# parse a compact ECDSA signature (64 bytes + recovery id)
# returns: 1 = deterministic; 0 = not deterministic
deterministic = secp256k1_lib.secp256k1_ecdsa_sign_recoverable(
privkey.ctx, # initialized context object
sig, # array where signature is held
digest, # 32-byte message hash being signed
privkey.private_key, # 32-byte secret key
secp256k1_ffi.NULL, # default nonce function
ndata, # incrementing nonce data
)
# signing large data is computationally expensive and time consuming
# the hash of the data is a relatively small
# signing hash is more efficient than signing serialization
digest = sha256(message).digest()
print(digest)
"""
ECDSA
eliptical curve digital signature algorithm
this is where the real hocus pocus lies
all of the ordering, typing, serializing, and digesting
culminates with the message meeting the wif
"""
# 8 bit string representation of private key
p = bytes(PrivateKey(wif))
# create some arbitrary data used by the nonce generation
ndata = secp256k1_ffi.new("const int *ndata")
ndata[0] = 0 # it adds "\0x00", then "\0x00\0x00", etc..
while True: # repeat process until deterministic and cannonical
ndata[0] += 1 # increment the arbitrary nonce
# obtain compiled/binary private key from the wif
privkey = secp256k1_PrivateKey(p, raw=True)
print(it('red',str(privkey)))
print(privkey)
# create a new recoverable 65 byte ECDSA signature
sig = secp256k1_ffi.new(
"secp256k1_ecdsa_recoverable_signature *"
)
# parse a compact ECDSA signature (64 bytes + recovery id)
# returns: 1 = deterministic; 0 = not deterministic
deterministic = secp256k1_lib.secp256k1_ecdsa_sign_recoverable(
privkey.ctx, # initialized context object
sig, # array where signature is held
# graphenebase/ecdsa.py stripped of non-secp256k1 methods
print(it('red',"verify_message...return phex"))
# require message and signature to be bytes
if not isinstance(message, bytes):
message = bytes(message, "utf-8")
if not isinstance(signature, bytes):
signature = bytes(signature, "utf-8")
digest = hashfn(message).digest()
sig = signature[1:]
# recover parameter only
recoverParameter = bytearray(signature)[0] - 4 - 27
# "bitwise or"; each bit of the output is 0
# if the corresponding bit of x AND of y is 0, otherwise it's 1
ALL_FLAGS = (
secp256k1_lib.SECP256K1_CONTEXT_VERIFY
| secp256k1_lib.SECP256K1_CONTEXT_SIGN
)
# ecdsa.PublicKey with additional functions to serialize
# in uncompressed and compressed formats
pub = secp256k1_PublicKey(flags=ALL_FLAGS)
# recover raw signature
sig = pub.ecdsa_recoverable_deserialize(sig, recoverParameter)
# recover public key
verifyPub = secp256k1_PublicKey(pub.ecdsa_recover(message, sig))
# convert recoverable sig to normal sig
normalSig = verifyPub.ecdsa_recoverable_convert(sig)
# verify
verifyPub.ecdsa_verify(message, normalSig)
phex = verifyPub.serialize(compressed=True)
return phex
print(it('red',"verify_message...return phex"))
# require message and signature to be bytes
if not isinstance(message, bytes):
message = bytes(message, "utf-8")
if not isinstance(signature, bytes):
signature = bytes(signature, "utf-8")
digest = hashfn(message).digest()
sig = signature[1:]
# recover parameter only
recoverParameter = bytearray(signature)[0] - 4 - 27
# "bitwise or"; each bit of the output is 0
# if the corresponding bit of x AND of y is 0, otherwise it's 1
ALL_FLAGS = (
secp256k1_lib.SECP256K1_CONTEXT_VERIFY
| secp256k1_lib.SECP256K1_CONTEXT_SIGN
)
# ecdsa.PublicKey with additional functions to serialize
# in uncompressed and compressed formats
pub = secp256k1_PublicKey(flags=ALL_FLAGS)
# recover raw signature
sig = pub.ecdsa_recoverable_deserialize(sig, recoverParameter)
# recover public key
verifyPub = secp256k1_PublicKey(pub.ecdsa_recover(message, sig))
# convert recoverable sig to normal sig
normalSig = verifyPub.ecdsa_recoverable_convert(sig)
# verify
verifyPub.ecdsa_verify(message, normalSig)
phex = verifyPub.serialize(compressed=True)
return phex
# create some arbitrary data used by the nonce generation
ndata = secp256k1_ffi.new("const int *ndata")
ndata[0] = 0 # it adds "\0x00", then "\0x00\0x00", etc..
while True: # repeat process until deterministic and cannonical
ndata[0] += 1 # increment the arbitrary nonce
# obtain compiled/binary private key from the wif
privkey = secp256k1_PrivateKey(p, raw=True)
print(it('red',str(privkey)))
print(privkey)
# create a new recoverable 65 byte ECDSA signature
sig = secp256k1_ffi.new(
"secp256k1_ecdsa_recoverable_signature *"
)
# parse a compact ECDSA signature (64 bytes + recovery id)
# returns: 1 = deterministic; 0 = not deterministic
deterministic = secp256k1_lib.secp256k1_ecdsa_sign_recoverable(
privkey.ctx, # initialized context object
sig, # array where signature is held
digest, # 32-byte message hash being signed
privkey.private_key, # 32-byte secret key
secp256k1_ffi.NULL, # default nonce function
ndata, # incrementing nonce data
)
if not deterministic:
print("not deterministic, try again...")
continue
# we derive the recovery paramter
# which simplifies the verification of the signature
# it links the signature to a single unique public key
# without this parameter, the back-end would need to test
# for multiple public keys instead of just one
signature, i = privkey.ecdsa_recoverable_serialize(sig)
# obtain compiled/binary private key from the wif
privkey = secp256k1_PrivateKey(p, raw=True)
print(it('red',str(privkey)))
print(privkey)
# create a new recoverable 65 byte ECDSA signature
sig = secp256k1_ffi.new(
"secp256k1_ecdsa_recoverable_signature *"
)
# parse a compact ECDSA signature (64 bytes + recovery id)
# returns: 1 = deterministic; 0 = not deterministic
deterministic = secp256k1_lib.secp256k1_ecdsa_sign_recoverable(
privkey.ctx, # initialized context object
sig, # array where signature is held
digest, # 32-byte message hash being signed
privkey.private_key, # 32-byte secret key
secp256k1_ffi.NULL, # default nonce function
ndata, # incrementing nonce data
)
if not deterministic:
print("not deterministic, try again...")
continue
# we derive the recovery paramter
# which simplifies the verification of the signature
# it links the signature to a single unique public key
# without this parameter, the back-end would need to test
# for multiple public keys instead of just one
signature, i = privkey.ecdsa_recoverable_serialize(sig)
# we ensure that the signature is canonical; simplest form
if canonical(signature):
# add 4 and 27 to stay compatible with other protocols
i += 4 # compressed
i += 27 # compact
# -*- coding: utf-8 -*-
from __future__ import print_function
import contextlib
import timeit
import secp256k1
from raiden.utils import sha3, privatekey_to_address
from raiden.messages import decode
from raiden.messages import (
Ack, ConfirmTransfer, DirectTransfer, Lock, MediatedTransfer, Ping,
RefundTransfer, Secret, SecretRequest, TransferTimeout,
)
GLOBAL_CTX = secp256k1.lib.secp256k1_context_create(secp256k1.ALL_FLAGS)
PRIVKEY_BIN = 'x' * 32
PRIVKEY = secp256k1.PrivateKey(PRIVKEY_BIN, ctx=GLOBAL_CTX, raw=True)
ADDRESS = privatekey_to_address(PRIVKEY_BIN)
HASH = sha3(PRIVKEY)
ITERATIONS = 1000000 # timeit default
def run_timeit(message_name, message, iterations=ITERATIONS):
data = message.encode()
def test_encode():
message.encode()
def test_decode():
decode(data)
def sign(data: str, private_key_seed_ascii: str):
data = eth_message_hex(data)
print("--eth_message_hex hash", data)
priv = private_key_seed_ascii
pk = PrivateKey(priv, raw=True)
signature = pk.ecdsa_recoverable_serialize(pk.ecdsa_sign_recoverable(data, raw=True))
signature = signature[0] + utils.bytearray_to_bytestr([signature[1]])
return signature, eth_privtoaddr(priv)
:param str wif: Private key in
"""
if not isinstance(message, bytes):
message = bytes(message, "utf-8")
digest = hashfn(message).digest()
priv_key = PrivateKey(wif)
p = bytes(priv_key)
if SECP256K1_MODULE == "secp256k1":
ndata = secp256k1.ffi.new("const int *ndata")
ndata[0] = 0
while True:
ndata[0] += 1
privkey = secp256k1.PrivateKey(p, raw=True)
sig = secp256k1.ffi.new("secp256k1_ecdsa_recoverable_signature *")
signed = secp256k1.lib.secp256k1_ecdsa_sign_recoverable(
privkey.ctx, sig, digest, privkey.private_key, secp256k1.ffi.NULL, ndata
)
if not signed == 1: # pragma: no cover
raise AssertionError()
signature, i = privkey.ecdsa_recoverable_serialize(sig)
if _is_canonical(signature):
i += 4 # compressed
i += 27 # compact
break
elif SECP256K1_MODULE == "cryptography":
cnt = 0
private_key = ec.derive_private_key(
int(repr(priv_key), 16), ec.SECP256K1(), default_backend()
)