Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
assert len(pub[2:].decode('hex')) == ecdsa.SECP256k1.verifying_key_length, "BUG: Invalid key decoding"
sk = ecdsa.SigningKey.from_string(priv.decode('hex'), curve=ecdsa.SECP256k1)
sig_bin = sk.sign_digest(data_hash.decode('hex'), sigencode=ecdsa.util.sigencode_der)
# enforce low-s
sig_r, sig_s = ecdsa.util.sigdecode_der( sig_bin, ecdsa.SECP256k1.order )
if sig_s * 2 >= ecdsa.SECP256k1.order:
log.debug("High-S to low-S")
sig_s = ecdsa.SECP256k1.order - sig_s
sig_bin = ecdsa.util.sigencode_der( sig_r, sig_s, ecdsa.SECP256k1.order )
# sanity check
vk = ecdsa.VerifyingKey.from_string(pub[2:].decode('hex'), curve=ecdsa.SECP256k1)
assert vk.verify_digest(sig_bin, data_hash.decode('hex'), sigdecode=ecdsa.util.sigdecode_der), "Failed to verify signature ({}, {})".format(sig_r, sig_s)
return base64.b64encode( bitcoin.encode_sig( None, sig_r, sig_s ).decode('hex') )
if(sig == "reward"):
newtrans = transaction(sender=payloaded["sender"],
senderwallet=wllt,
receiver=payloaded["receiver"],
prevblockhash=transaction.objects.all().last().blockhash,
blockhash=payloaded["blockhash"],
amount=payloaded["amount"],
nonce=payloaded["nonce"],
first_timestamp=payloaded["timestamp"],
P2PKH=payloaded["P2PKH"],
verification=True
).save()
else:
try:
sigbyte = bytes.fromhex(sig)
vk = VerifyingKey.from_string(bytes.fromhex(payloaded["sender"]), curve=SECP256k1)
tt = vk.verify(sigbyte, datashash.encode('utf-8')) # True
except BadSignatureError:
print("unbelieveable")
data["response"] = "unbelieveable"
newtrans = transaction(sender=payloaded["sender"],
senderwallet=wllt,
receiver=payloaded["receiver"],
prevblockhash=transaction.objects.all().last().blockhash,
blockhash=payloaded["blockhash"],
amount=payloaded["amount"],
nonce=payloaded["nonce"],
first_timestamp=payloaded["timestamp"],
P2PKH=payloaded["P2PKH"],
verification=False
).save()
print("badsignature")
def validate_tx_in(tx_in, transaction, a_unspent_tx_outs):
referenced_utxo = [utxo for utxo in a_unspent_tx_outs if utxo.tx_out_id == tx_in.tx_out_id and utxo.tx_out_index == tx_in.tx_out_index][0]
if referenced_utxo == []:
print('referenced txOut not found: ' + json.dumps(tx_in))
return False
address = referenced_utxo.address
vk = VerifyingKey.from_string(bytes.fromhex(address), curve=SECP256k1)
try:
vk.verify(bytes.fromhex(tx_in.signature), transaction.id.encode())
except Exception as e:
# change the exception
print('invalid tx_in signature: %s txId: %s address: %s' % (tx_in.signature, transaction.id, referenced_utxo.address))
return False
return True
# 1.1
x = r + (recid//2) * order
# 1.3
alpha = ( x * x * x + curve.a() * x + curve.b() ) % curve.p()
beta = modular_sqrt(alpha, curve.p())
y = beta if (beta - recid) % 2 == 0 else curve.p() - beta
# 1.4 the constructor checks that nR is at infinity
R = Point(curve, x, y, order)
# 1.5 compute e from message:
h = Hash( msg_magic(message) )
e = string_to_number(h)
minus_e = -e % order
# 1.6 compute Q = r^-1 (sR - eG)
inv_r = numbertheory.inverse_mod(r,order)
Q = inv_r * ( s * R + minus_e * G )
public_key = ecdsa.VerifyingKey.from_public_point( Q, curve = SECP256k1 )
# check that Q is the public key
public_key.verify_digest( sig[1:], h, sigdecode = ecdsa.util.sigdecode_string)
# check that we get the original signing address
addr = public_key_to_bc_address( point_to_ser(public_key.pubkey.point, compressed) )
if address != addr:
raise Exception("Bad signature")
def can_bypass(chal, sol):
from ecdsa import VerifyingKey
from ecdsa.util import sigdecode_der
if not sol.startswith('b.'):
return False
sig = bytes.fromhex(sol[2:])
with open("/kctf/pow-bypass/pow-bypass-key-pub.pem", "r") as fd:
vk = VerifyingKey.from_pem(fd.read())
return vk.verify(signature=sig, data=bytes(chal, 'ascii'), hashfunc=hashlib.sha256, sigdecode=sigdecode_der)
def verify_signature(data, signature, pubkey):
"""
Verify a signature.
If the signature is valid, returns True. If the signature is invalid, raise
an exception explaining why.
"""
if isinstance(data, str):
data = data.encode()
# Add data template
data = b'Content-Signature:\x00' + data
try:
verifying_pubkey = ecdsa.VerifyingKey.from_pem(pubkey)
except binascii.Error as e:
if e.args == ('Incorrect padding',):
raise WrongPublicKeySize()
else:
raise
except IndexError as e:
raise WrongPublicKeySize()
try:
signature = base64.urlsafe_b64decode(signature)
except binascii.Error as e:
if e.args == ('Incorrect padding',):
raise WrongSignatureSize()
else:
raise
def __init__(self, pubkey, chain_code, n, depth, parent=None):
super().__init__(chain_code, n, depth, parent)
if isinstance(pubkey, ecdsa.VerifyingKey):
self.verifying_key = pubkey
else:
self.verifying_key = self._verifying_key_from_pubkey(pubkey)
self.addresses = {}
def point(self):
""" Return the point for the public key """
string = unhexlify(self.unCompressed())
return ecdsa.VerifyingKey.from_string(
string[1:], curve=ecdsa.SECP256k1).pubkey.point
def _CKD_pub(cK, c, s):
order = generator_secp256k1.order()
I = hmac.new(c, cK + s, hashlib.sha512).digest()
curve = SECP256k1
pubkey_point = string_to_number(I[0:32]) * curve.generator + ser_to_point(cK)
public_key = ecdsa.VerifyingKey.from_public_point(pubkey_point, curve=SECP256k1)
c_n = I[32:]
cK_n = GetPubKey(public_key.pubkey, True)
return cK_n, c_n