def __init__(self, msg=None, data=None, filename=None, password=None, vals=None, file_obj=None): self.verifying_key = None self.signing_key = None if file_obj is not None: self._from_private_key(file_obj, password) return if filename is not None: self._from_private_key_file(filename, password) return if (msg is None) and (data is not None): msg = Message(data) if vals is not None: self.verifying_key, self.signing_key = vals else: if msg is None: raise SSHException('Key object may not be empty') if msg.get_text() != 'ecdsa-sha2-nistp256': raise SSHException('Invalid key') curvename = msg.get_text() if curvename != 'nistp256': raise SSHException("Can't handle curve of type %s" % curvename) pointinfo = msg.get_binary() if pointinfo[0:1] != four_byte: raise SSHException('Point compression is being used: %s' % binascii.hexlify(pointinfo)) self.verifying_key = VerifyingKey.from_string(pointinfo[1:], curve=curves.NIST256p) self.size = 256
def import_public_key_ecc(s): """ import public ecc key from a hex string :param s: a hex string generated by export_keys() :return: a VerifyingKey object """ return VerifyingKey.from_string(bytes.fromhex(s), curve=SECP256k1)
def __init__(self,jsonObject): """ Validate the signature of an already parsed JSON object The current implementation is limited to RSA and EC signatures and usage of the IETF JOSE algorithms An invalid signature raises an exception """ if not isinstance(jsonObject, OrderedDict): raise TypeError('JCS requires JSON to be parsed into a "OrderedDict"') signatureObject = jsonObject['signature'] clonedSignatureObject = OrderedDict(signatureObject) signatureValue = base64UrlDecode(signatureObject.pop('value')) algorithmEntry = getAlgorithmEntry(signatureObject['algorithm']) hashObject = algorithmEntry[1].new(serializeJson(jsonObject).encode("utf-8")) jsonObject['signature'] = clonedSignatureObject self.publicKey = signatureObject['publicKey'] keyType = self.publicKey['type'] if algorithmEntry[0]: if keyType != 'RSA': raise TypeError('"RSA" expected') self.nativePublicKey = RSA.construct([cryptoBigNumDecode(self.publicKey['n']), cryptoBigNumDecode(self.publicKey['e'])]) if not PKCS1_v1_5.new(self.nativePublicKey).verify(hashObject,signatureValue): raise ValueError('Invalid Signature!') else: if keyType != 'EC': raise TypeError('"EC" expected') self.nativePublicKey = EC.from_string(base64UrlDecode(self.publicKey['x']) + base64UrlDecode(self.publicKey['y']), curve=getEcCurve(self.publicKey['curve'])) self.nativePublicKey.verify_digest(signatureValue,hashObject.digest())
def check_for_privkey(keydir, jid, stderr): # the "anonymous ID" case if jid.startswith("anonid0-"): return None # the "old-style ID" case # FIXME: once it is possible for addons to change from old-style IDs # to new, cryptographic IDs on AMO and in Firefox, warn users that # continuing to use old-style IDs is less secure, and provide them with # instructions for changing to new IDs. if not jid.startswith("jid0-"): return None keypath = os.path.join(keydir, jid) if not os.path.isfile(keypath): msg = """\ Your package.json says our ID is: %(jid)s But I don't have a corresponding private key in: %(keypath)s If you are the original developer of this package and have recently copied the source code from a different machine to this one, you should copy the private key into the file named above. Otherwise, if you are a new developer who has made a copy of an existing package to use as a starting point, you need to remove the 'id' property from package.json, so that we can generate a new id and keypair. This will disassociate our new package from the old one. If you're collaborating on the same addon with a team, make sure at least one person on the team has the private key. In the future, you may not be able to distribute your addon without it. """ print >> stderr, msg % {"jid": jid, "keypath": keypath} return None keylines = open(keypath, "r").readlines() keydata = {} for line in keylines: line = line.strip() if line: k, v = line.split(":", 1) keydata[k.strip()] = v.strip() if "private-key" not in keydata: raise ValueError("invalid keydata: can't find 'private-key' line") sk_s = remove_prefix(keydata["private-key"], "private-jid0-", errormsg="unable to parse private-key data") from ecdsa import SigningKey, VerifyingKey, NIST256p sk = SigningKey.from_string(my_b32decode(sk_s), curve=NIST256p) vk = sk.get_verifying_key() jid_2 = vk_to_jid(vk) if jid_2 != jid: raise ValueError("invalid keydata: private-key in %s does not match" " public key for %s" % (keypath, jid)) vk_s = remove_prefix(keydata["public-key"], "public-jid0-", errormsg="unable to parse public-key data") vk2 = VerifyingKey.from_string(my_b32decode(vk_s), curve=NIST256p) if vk.to_string() != vk2.to_string(): raise ValueError("invalid keydata: public-key mismatch") return sk
def hex2key(hex_key): key_bytes = unhexlify(hex_key) if len(hex_key) == 64: return SigningKey.from_string(key_bytes, curve=NIST256p, hashfunc=sha256) elif len(hex_key) == 128: return VerifyingKey.from_string(key_bytes, curve=NIST256p, hashfunc=sha256) else: raise ValueError("Key in hex form is of the wrong length.")
def __init__(self, identity, private, public): """Configure HTDSA signed request/response authentication. To perform the cryptographic operations required for the HTDSA protocol you must pass in either instances of `ecdsa` signing and verifying keys, or their hex-encoded versions which will be converted automatically. Additionally, the identity token (opaque identifier) assigned to your client application by the provider will need to be passed in so we can identify ourselves. The private key is your application's private key. The public key is the provider's service key you were given when registering your application. """ self.identity = identity self.private = SigningKey.from_string(unhexlify(private), NIST256p) if isinstance(private, (str, unicode)) else private self.public = VerifyingKey.from_string(unhexlify(public), NIST256p) if isinstance(public, (str, unicode)) else public
def __init__(self, key=None, private=False): self.secretKey = self.verifKey = None # Recuperation if key is not None: if private: self.secretKey = SigningKey.from_string(key, curve=NIST384p) self.verifKey = self.secretKey.get_verifying_key() else: self.verifKey = VerifyingKey.from_string(key, curve=NIST384p) # Auto-generation else: self.secretKey = SigningKey.generate(curve=NIST384p) self.verifKey = self.secretKey.get_verifying_key()
def check_for_privkey(keydir, jid, stderr): keypath = os.path.join(keydir, jid) if not os.path.isfile(keypath): msg = """\ Your package.json says our ID is: %(jid)s But I don't have a corresponding private key in: %(keypath)s If you are the original developer of this package and have recently copied the source code from a different machine to this one, you need to copy the private key into the file named above. Otherwise, if you are a new developer who has made a copy of an existing package to use as a starting point, you need to remove the 'id' property from package.json, so that we can generate a new id and keypair. This will disassociate our new package from the old one. """ print >>stderr, msg % {"jid": jid, "keypath": keypath} return None keylines = open(keypath, "r").readlines() keydata = {} for line in keylines: line = line.strip() if line: k,v = line.split(":", 1) keydata[k.strip()] = v.strip() if "private-key" not in keydata: raise ValueError("invalid keydata: can't find 'private-key' line") sk_s = remove_prefix(keydata["private-key"], "private-jid0-", errormsg="unable to parse private-key data") from ecdsa import SigningKey, VerifyingKey, NIST256p sk = SigningKey.from_string(my_b32decode(sk_s), curve=NIST256p) vk = sk.get_verifying_key() jid_2 = vk_to_jid(vk) if jid_2 != jid: raise ValueError("invalid keydata: private-key in %s does not match" " public key for %s" % (keypath, jid)) vk_s = remove_prefix(keydata["public-key"], "public-jid0-", errormsg="unable to parse public-key data") vk2 = VerifyingKey.from_string(my_b32decode(vk_s), curve=NIST256p) if vk.to_string() != vk2.to_string(): raise ValueError("invalid keydata: public-key mismatch") return sk
def valid_signature(self, signature, msg, public_key=None): try: if type(msg) == str: msg = msg.encode("ascii") #Parse public key. if public_key == None: public_key = self.public_key else: public_key = self.parse_public_key(public_key) signature = auto_bytes(signature) msg = auto_bytes(msg) verify_key = VerifyingKey.from_string(public_key, SECP256k1) return verify_key.verify(signature, msg) except Exception as e: print(e) return 0
def __init__(self, public_key=None, private_key=None): self.id = 0 if public_key is not None: public_key = "#" + public_key if private_key is not None: private_key = "#" + private_key self.public_key = auto_bytes(public_key) self.private_key = private_key self.addr_version = None self.use_compression = 1 if private_key == "": private_key = None #Generate key pairs. if self.public_key == None and private_key == None: self.sign_key = SigningKey.generate(curve=SECP256k1) self.verify_key = self.sign_key.get_verifying_key() self.private_key = self.sign_key.to_string() self.public_key = self.verify_key.to_string() return #Init public key. self.old_verify_str = None if self.public_key != None: self.public_key = self.parse_public_key(self.public_key) self.verify_key = VerifyingKey.from_string(self.public_key, SECP256k1) self.sign_key = None self.old_verify_str = self.verify_key.to_string() #Init private key. if self.private_key != None: #Construct keys from private key. self.private_key = self.parse_private_key(private_key) self.sign_key = SigningKey.from_string(self.private_key, SECP256k1) self.verify_key = self.sign_key.get_verifying_key() #Check private key corrosponds to public key. if self.old_verify_str != None: if self.old_verify_str != self.verify_key.to_string(): raise Exception("Private key doesn't corrospond to stored public key.")
def from_sec(string, curve=curves.SECP256k1, hashfunc=sha1, validate_point=True): """Convert a public key in SEC binary format to a verifying key.""" # based on code from https://github.com/richardkiss/pycoin if string.startswith(b("\x04")): # uncompressed return VerifyingKey.from_string(string[1:], curve, hashfunc, validate_point) elif string.startswith(b("\x02")) or string.startswith(b("\x03")): # compressed is_even = string.startswith(b("\x02")) x = string_to_number(string[1:]) order = curve.order p = curve.curve.p() alpha = (pow(x, 3, p) + (curve.curve.a() * x) + curve.curve.b()) % p beta = square_root_mod_prime(alpha, p) if is_even == bool(beta & 1): y = p - beta else: y = beta if validate_point: assert ecdsa.point_is_valid(curve.generator, x, y) point = ellipticcurve.Point(curve.curve, x, y, order) return VerifyingKey.from_public_point(point, curve, hashfunc)
def verify(public, signature, message): """ The function verify if a signature correspond to a message """ # We turn the message into bytes if the message is in string if isinstance(message, str): message = message.encode("utf-8") # We transform the signature in a signature with bytes if isinstance(signature, str): signature = binascii.unhexlify(signature) # We create an object for the public key public = binascii.unhexlify(public) public = VerifyingKey.from_string(public) # We verify the key try: public.verify(signature, message) return True except BadSignatureError: return False
def DecryptMessage(privateKey_hex, encrypted_hex): if privateKey_hex[:2] == '0x': privateKey_hex = privateKey_hex[2:] if encrypted_hex[:2] == '0x': encrypted_hex = encrypted_hex[2:] # get the components encrypted = bytearray.fromhex(encrypted_hex) iv = encrypted[:16] ephemPubKeyEncoded = encrypted[17:81] mac = encrypted[81:113] ciphertext = encrypted[113:] # recover the temporary public key ephemPubKey = VerifyingKey.from_string(ephemPubKeyEncoded, curve=SECP256k1) # load the private key priv_key = SigningKey.from_secret_exponent(int(privateKey_hex, 16), curve=SECP256k1) ecdh = ECDH(curve=SECP256k1, private_key=priv_key) # ECDH => get the shared secret ecdh.load_received_public_key(ephemPubKey) px = ecdh.generate_sharedsecret_bytes() # compute the encription and MAC keys hash_px = SHA512.new(data=px).digest() encryptionKey = hash_px[:32] macKey = hash_px[32:] # check the MAC dataToMac = iv + bytearray([4]) + ephemPubKeyEncoded + ciphertext computed_mac = hmac.new(macKey, dataToMac, 'sha256').digest() if computed_mac != mac: raise ValueError("MAC missmatch") #decipher the text plaintext = AES256CbcDecrypt(ciphertext.hex(), encryptionKey, iv) return plaintext.decode("utf-8")
def mine(self): """ PoA signer; seals a block with new seal data by signing it, checking that signature is valid, and returning. """ # Use NIST192p curve and ECDSA, encoding block header as UTF-8 # use self.get_private_key() for key # encode result as int and set using set_seal_data # make sure to check that output is valid seal with provided code # (if seal is invalid, repeat) seal_valid = False while not seal_valid: sk = SigningKey.from_string(self.get_private_key(), curve=NIST192p) vk = VerifyingKey.from_string(self.get_public_key(), curve=NIST192p) signature = sk.sign(self.unsealed_header().encode('utf-8')) self.set_seal_data(ecdsa.util.string_to_number(signature)) seal_valid = self.seal_is_valid() # Placeholder for (1b) return
def VerifySignature(message, signature, public_key): """ Verify the integrity of the message. Args: message (str): the message to verify. signature (bytearray): the signature belonging to the message. public_key (ECPoint|bytes): the public key to use for verifying the signature. If `public_key` is of type bytes then it should be raw bytes (i.e. b'\xAA\xBB'). Returns: bool: True if verification passes. False otherwise. """ Crypto.SetupSignatureCurve() if type(public_key) is EllipticCurve.ECPoint: pubkey_x = public_key.x.value.to_bytes(32, 'big') pubkey_y = public_key.y.value.to_bytes(32, 'big') public_key = pubkey_x + pubkey_y m = message try: m = binascii.unhexlify(message) except Exception as e: logger.error("could not get m: %s" % e) if len(public_key) == 33: public_key = bitcoin.decompress(public_key) public_key = public_key[1:] try: vk = VerifyingKey.from_string(public_key, curve=NIST256p, hashfunc=hashlib.sha256) res = vk.verify(signature, m, hashfunc=hashlib.sha256) return res except Exception as e: pass return False
def EncryptMessage(publicKey_hex, plainText_string): if publicKey_hex[:2] == '0x': publicKey_hex = publicKey_hex[2:] publicKey_bin = bytearray.fromhex(publicKey_hex) # Generate the temporary key ecdh = ECDH(curve=SECP256k1) ecdh.generate_private_key() ephemPubKeyEncoded = bytearray.fromhex( ecdh.get_public_key().to_string().hex()) # Load the public key publicKey = VerifyingKey.from_string(publicKey_bin, curve=SECP256k1) # ECDH => get the shared secret ecdh.load_received_public_key(publicKey) px = ecdh.generate_sharedsecret_bytes() # compute the encription and MAC keys hash_px = SHA512.new(data=px).digest() encryptionKey = hash_px[:32] macKey = hash_px[32:] # cipher the plain text iv = Random.get_random_bytes(16) plaintext = plainText_string.encode(encoding='utf_8') ciphertext = AES256CbcEncrypt(plaintext, encryptionKey, iv) # compute the MAC dataToMac = iv + bytearray([4]) + ephemPubKeyEncoded + ciphertext mac = hmac.new(macKey, dataToMac, 'sha256').digest() #build the output serializedCiphertext = iv + bytearray( [4]) + ephemPubKeyEncoded + mac + ciphertext return serializedCiphertext.hex()
def __init__(self, public_key=None, private_key=None): self.id = 0 self.public_key = auto_bytes(public_key) self.private_key = private_key self.addr_version = None self.use_compression = 1 if private_key == "": private_key = None #Generate key pairs. if self.public_key == None and private_key == None: self.sign_key = SigningKey.generate(curve=SECP256k1) self.verify_key = self.sign_key.get_verifying_key() self.private_key = self.sign_key.to_string() self.public_key = self.verify_key.to_string() return #Init public key. self.old_verify_str = None if self.public_key != None: self.public_key = self.parse_public_key(self.public_key) self.verify_key = VerifyingKey.from_string(self.public_key, SECP256k1) self.sign_key = None self.old_verify_str = self.verify_key.to_string() #Init private key. if self.private_key != None: #Construct keys from private key. self.private_key = self.parse_private_key(private_key) self.sign_key = SigningKey.from_string(self.private_key, SECP256k1) self.verify_key = self.sign_key.get_verifying_key() #Check private key corrosponds to public key. if self.old_verify_str != None: if self.old_verify_str != self.verify_key.to_string(): raise Exception( "Private key doesn't corrospond to stored public key.")
def __init__(self, msg=None, data=None, filename=None, password=None, vals=None, file_obj=None, validate_point=True): self.verifying_key = None self.signing_key = None if file_obj is not None: self._from_private_key(file_obj, password) return if filename is not None: self._from_private_key_file(filename, password) return if (msg is None) and (data is not None): msg = Message(data) if vals is not None: self.signing_key, self.verifying_key = vals else: if msg is None: raise SSHException('Key object may not be empty') if msg.get_text() != 'ecdsa-sha2-nistp256': raise SSHException('Invalid key') curvename = msg.get_text() if curvename != 'nistp256': raise SSHException("Can't handle curve of type %s" % curvename) pointinfo = msg.get_binary() if pointinfo[0:1] != four_byte: raise SSHException('Point compression is being used: %s' % binascii.hexlify(pointinfo)) self.verifying_key = VerifyingKey.from_string( pointinfo[1:], curve=curves.NIST256p, validate_point=validate_point) self.size = 256
def is_signature_valid(message, signature, public_key): """Validate if a message has a valid signature Args: message (String): the message which has been signed signature (String): the signature of the message public_key (String): the public key Return: (Logical): True if the message has been signed by the public key """ try: vk = VerifyingKey.from_string(bytes.fromhex(public_key)) return vk.verify(bytes.fromhex(signature), message.encode('utf-8')) except AssertionError: # The key is not valid return False except BadSignatureError: # The signature is not valid return False return False
def check_signature(key, sign): try: private_key = hex(base62.decode(key))[2:] except ValueError: print("The key has invalid characters") return False try: private_key = binascii.unhexlify(private_key) except binascii.Error: print("The key is invalid") return False try: private_key = SigningKey.from_string(private_key, curve=SECP256k1) except AssertionError: print("The key is invalid") return False public_key = binascii.hexlify( private_key.get_verifying_key().to_string()).decode('utf-8') vk = VerifyingKey.from_string(bytes.fromhex(public_key), curve=SECP256k1) try: return vk.verify(bytes.fromhex(sign), 'database'.encode('utf-8')) except BadSignatureError: return False
def ec_mult(self, his_pubkey): # - second call: given the pubkey of far side, calculate the shared pt on curve # - creates session key based on that from ecdsa.curves import SECP256k1 from ecdsa import VerifyingKey from ecdsa.util import number_to_string # Validate his pubkey a little: this call will check it's on the curve. assert len(his_pubkey) == 64 his_pubkey = VerifyingKey.from_string(his_pubkey, curve=SECP256k1, hashfunc=sha256) #print("his pubkey = %s" % b2a_hex(his_pubkey.to_string())) # do the D-H thing pt = self.my_key.privkey.secret_multiplier * his_pubkey.pubkey.point # final key is sha256 of that point, serialized (64 bytes). order = SECP256k1.order kk = number_to_string(pt.x(), order) + number_to_string(pt.y(), order) del self.my_key return sha256(kk).digest()
def mitm_verify(self, sig, expected_xpub): # First try with Pycoin try: from pycoin.key.BIP32Node import BIP32Node from pycoin.contrib.msg_signing import verify_message from pycoin.encoding import from_bytes_32 from base64 import b64encode mk = BIP32Node.from_wallet_key(expected_xpub) return verify_message(mk, b64encode(sig), msg_hash=from_bytes_32(self.session_key)) except ImportError: pass # If Pycoin is not available, do it using ecdsa from ecdsa import BadSignatureError, SECP256k1, VerifyingKey pubkey, chaincode = decode_xpub(expected_xpub) vk = VerifyingKey.from_string(get_pubkey_string(pubkey), curve=SECP256k1) try: ok = vk.verify_digest(sig[1:], self.session_key) except BadSignatureError: ok = False return ok
def wrapper(*args, **kwargs): logger.debug('Authorizing request') if 'Pub' not in request.headers: raise MissingParameterError('Missing authorization parameter: ' 'ECDSA public key') if 'Nonce' not in request.headers: raise MissingParameterError('Missing authorization parameter: ' 'Nonce') if 'Signature' not in request.headers: raise MissingParameterError('Missing authorization parameter: ' 'Signature') key = b64decode(request.headers['Pub'].encode()) nonce = request.headers['Nonce'].encode() signature = b64decode(request.headers['Signature'].encode()) if not database.has_key(key): raise AuthorizationError('ECDSA public key is unregistered') database.use_nonce(nonce) # throws exception on re-use vk = VerifyingKey.from_string(key, curve=CURVE) vk.verify(signature, nonce) return fn(pub=key)
def load_keys(pos_filename='poswallet.json'): global PUB_KEY global PRIV_KEY global ADDRESS if not os.path.exists(pos_filename): # Create new keys if none there. gen_keys_file(pos_filename) with open(pos_filename, 'r') as fp: wallet = json.load(fp) # TODO: handle encrypted wallet PRIV_KEY = SigningKey.from_string(b64decode( wallet['privkey'].encode('ascii')), curve=SECP256k1) # TODO: We could verify pubkey also, and warn if there is an error PUB_KEY = VerifyingKey.from_string(b64decode( wallet['pubkey'].encode('ascii')), curve=SECP256k1) # We recreate address rather than relying on address.txt ADDRESS = pub_key_to_addr(PUB_KEY.to_string()) assert ADDRESS == wallet['address'] if common.VERBOSE: print("Loaded address ", ADDRESS) print("Loaded pubkey ", raw_to_hex(PUB_KEY.to_string())) return True
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
def verify(pub_key, data, signature, hashfunc=sha256, curve=curve.P256, sign_fmt='DER', sign_size=32, pub_key_fmt='RAW'): data_bytes = data.encode() if pub_key_fmt == 'RAW': pub_key_encoded = pub_key elif pub_key_fmt == '04': pub_key_encoded = pub_key[2:] else: raise UnknownPublicKeyFormatError("fmt: '%s'" % pub_key_fmt) if sign_fmt in ['RAW', 'DER']: r, s = decode_sig(bytes.fromhex(signature), fmt=sign_fmt) signature = encode_sig(r, s, fmt='RAW', size=sign_size) else: raise UnknownSignatureFormatError("fmt: '%s'" % sign_fmt) vk = VerifyingKey.from_string(bytes.fromhex(pub_key_encoded), curve=curve, hashfunc=hashfunc) try: vk.verify(signature, data_bytes) return True except BadSignatureError: return False
def validate_signature(self, transaction_pool, transaction, chain): transaction_content = transaction["TYPE"] for input_block in transaction["INPUT"]: transaction_content += input_block[0] transaction_content += str(input_block[1]) for output_set in transaction["OUTPUT"]: transaction_content += output_set[0] transaction_content += str(output_set[1]) for i in range(len(transaction["SIGNATURE"])): input_block = transaction["INPUT"][i] verifying_key = None for k in range(len(chain) - 1, -1, -1): if input_block[0] == chain[k].transactions[1]["NUMBER"]: verifying_key = VerifyingKey.from_string( bytes.fromhex(chain[k].transactions[1]["OUTPUT"][ input_block[1]][0])) if verifying_key is not None: signature = transaction["SIGNATURE"][i] try: verifying_key.verify(bytes.fromhex(signature), transaction_content.encode("utf-8")) transaction_content += signature except BadSignatureError: print("Invalid signature") self.remove_transaction(transaction_pool, transaction, "Invalid signature") return False else: return False return True
def verifyFn(sig, public_key, msg): vk = VerifyingKey.from_string(public_key, curve=SECP256k1) return vk.verify(sig, msg) # True
def string_to_pub(self, pub): return VerifyingKey.from_string(bytearray.fromhex(pub), curve=self.curve)
def pop_auth_values(post_dict): endpoint = post_dict.pop('coreproxy_endpoint') identity = post_dict.pop('coreproxy_identity') private = SigningKey.from_string(unhexlify(post_dict.pop('coreproxy_private')), curve=NIST256p, hashfunc=sha256) public = VerifyingKey.from_string(unhexlify(post_dict.pop('coreproxy_public')), curve=NIST256p, hashfunc=sha256) return endpoint, identity, private, public
def Verify(self, issuer = None): if issuer == None: issuer = self sigAlgo = self.SignatureAlgorithm() CertDer = encoder.encode(self.Asn1Obj.getComponentByName('tbsCertificate')) if sigAlgo == 'sha1WithRSAEncryption' or sigAlgo == 'ecdsa-with-SHA1': from Crypto.Hash import SHA SigHash = SHA.new(CertDer) elif sigAlgo == 'sha256WithRSAEncryption' or sigAlgo == 'ecdsa-with-SHA256': from Crypto.Hash import SHA256 SigHash = SHA256.new(CertDer) elif sigAlgo == 'sha384WithRSAEncryption' or sigAlgo == 'ecdsa-with-SHA384': from Crypto.Hash import SHA384 SigHash = SHA384.new(CertDer) elif sigAlgo == 'sha512WithRSAEncryption' or sigAlgo == 'ecdsa-with-SHA512': from Crypto.Hash import SHA512 SigHash = SHA512.new(CertDer) elif sigAlgo == 'sha224WithRSAEncryption' or sigAlgo == 'ecdsa-with-SHA224': from Crypto.Hash import SHA224 SigHash = SHA224.new(CertDer) elif sigAlgo == 'md2WithRSAEncryption': from Crypto.Hash import MD2 SigHash = MD2.new(CertDer) elif sigAlgo == 'md4WithRSAEncryption': from Crypto.Hash import MD4 SigHash = MD4.new(CertDer) elif sigAlgo == 'md5WithRSAEncryption': from Crypto.Hash import MD5 SigHash = MD5.new(CertDer) else: raise NotImplementedError('Signature algorithm not supported ({0})'.format(sigAlgo)) if issuer.PublicKeyAlgorithm() == 'rsaEncryption': from Crypto.PublicKey import RSA from Crypto.Signature import PKCS1_v1_5 PubKeyDer = issuer.PublicKey().Raw() key = RSA.importKey(PubKeyDer) verifier = PKCS1_v1_5.new(key) try: if verifier.verify(SigHash, self.Signature()): return True else: return False except ValueError: return False elif issuer.PublicKeyAlgorithm() == 'id-ecPublicKey': from ecdsa import VerifyingKey, NIST192p, NIST224p, NIST256p, NIST384p, NIST521p, SECP256k1 from ecdsa.util import sigdecode_der curves = [NIST192p, NIST224p, NIST256p, NIST384p, NIST521p, SECP256k1] TheCurve = None for crv in curves: if crv.name == issuer.PublicKey().CurveMap(): TheCurve = crv break if TheCurve == None: raise NotImplementedError('Public Key Curve not supported ({0})'.format(issuer.PublicKey().CurveMap())) VerKey = VerifyingKey.from_string(issuer.PublicKey().Raw(), curve=TheCurve) try: if VerKey.verify_digest(self.Signature(), SigHash.digest(), sigdecode=sigdecode_der): return True else: return False except: return False else: raise NotImplementedError('Public key algorithm not supported ({0})'.format(issuer.PublicKeyAlgorithm()))
print("Public key: ", pub.hex()) print("Address: 0x" + address) #priv = SigningKey.generate(curve=SECP256k1) #pub = priv.get_verifying_key() #print(priv.to_string()) #print(pub.to_string()) #print(priv.to_string().hex()) #print(pub.to_string().hex()) #privB: b"@\xb7:\x08\x86\x16\xde\x8a.sY\x1c\xd3\x1be'\xe8\xa0\x87h\x8b\xae\xd9\x16y\x87\x8cphq*\x13" #pubB = b'\xa1\xfdo\xdc\x9b\xd0s\xad1:\x93\xb2\xe5\x92\xac\x993\xd5\xae\x17\x83\xb7Z\x007to\x9c\xc7G\xbc\x88DE\xf0\x94$OZK\x1e{\x80\xd4\xb0\xedp\x17Kv\xae\x17\xe9\xec\x9a\xaa\xa9qP\xe7\x11\xae\\?' privT = '40b73a088616de8a2e73591cd31b6527e8a087688baed91679878c7068712a13' pubT = 'a1fd6fdc9bd073ad313a93b2e592ac9933d5ae1783b75a0037746f9cc747bc884445f094244f5a4b1e7b80d4b0ed70174b76ae17e9ec9aaaa97150e711ae5c3f' privB = bytes.fromhex(privT) pubB = bytes.fromhex(pubT) print(privB) print(pubB) sk = SigningKey.from_string(privB, curve=SECP256k1) vk = VerifyingKey.from_string(pubB, curve=SECP256k1) print(sk.to_string().hex()) print(vk.to_string().hex()) print ('------------------------------') mes = 'i love sex'.encode() sign = sk.sign(mes) print(sign.hex()) print(vk.verify(sign, mes)) assert vk.verify(sign, mes)
def verify_message(self, message, pubKey, signature): vk = VerifyingKey.from_string(bytearray.fromhex(pubKey)) return vk.verify(bytearray.fromhex(signature), message.encode("utf-8"))
def from_bytes(cls, b: bytes) -> 'PublicKey': if len(b) == 65: b = b[1:] # remove 0x04 prefix return cls(VerifyingKey.from_string(b, curve=SECP256k1))
def main(sk_filename): global processed_txids, transaction_id sk = SigningKey.from_pem(open(sk_filename).read()) vk = sk.get_verifying_key() pk = str(base64.b64encode(vk.to_string()), encoding='utf8') timestamp = str(int(time.time()-300)) leaders = db.query("SELECT * FROM leaders WHERE pk = %s AND timestamp > %s", pk, timestamp) if not leaders: election(sk_filename) else: # leader = leaders[0] transactions = db.query("SELECT * FROM transactions WHERE id > %s ORDER BY id ASC LIMIT 20", transaction_id) random.shuffle(transactions) for transaction in transactions: if transaction.txid in processed_txids: continue data = json.loads(transaction.data) sender = data["transaction"]["sender"] receiver = data["transaction"]["receiver"] amount = data["transaction"]["amount"] signature = data["signature"] chain_txids = set() sender_blocks = lastest_block(sender) receiver_blocks = lastest_block(receiver) if len(set(sender_blocks+receiver_blocks)) >= 1: if len(set(sender_blocks+receiver_blocks)) == 1: txs = db.query("SELECT * FROM graph WHERE hash = %s", (sender_blocks+receiver_blocks)[0]) else: txs = db.query("SELECT * FROM graph WHERE hash IN %s", set(sender_blocks+receiver_blocks)) for tx in txs: tx_data = json.loads(tx.data) txid = tx_data["transaction"]["txid"] chain_txids.add(txid) processed_txids.add(txid) if transaction.txid in chain_txids: continue from_block = sender_blocks[-1] if sender_blocks else sender to_block = receiver_blocks[-1] if receiver_blocks else receiver # query from_block and to_block # get balance and calcuate # update transaction's from_block and to_block data["from_block"] = from_block data["to_block"] = to_block data["sender_balance"] = "" data["receiver_balance"] = "" data["leader_publickey"] = pk vk2 = VerifyingKey.from_string(base64.b64decode(sender), curve=NIST384p) assert vk2.verify(base64.b64decode(signature), json.dumps(data["transaction"]).encode('utf-8')) # signature = sk.sign(json.dumps(transaction).encode('utf-8')) # data = {"transaction": transaction, "signature": str(base64.b64encode(signature), encoding="utf-8")} for nonce in range(100000000): block_hash = hashlib.sha256((json.dumps(data) + pk + str(nonce)).encode('utf8')).hexdigest() if block_hash < certain_value: print("tx", nonce, block_hash) try: # query if any node taken from_block or to_block db.execute("INSERT INTO graph (hash, from_block, to_block, sender, receiver, nonce, data) VALUES (%s, %s, %s, %s, %s, %s, %s)", block_hash, from_block, to_block, sender, receiver, nonce, transaction.data) # db.execute("INSERT INTO graph (hash, from_block, to_block, sender, receiver, nonce, data, transaction_id, timestamp) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)", block_hash, from_block, to_block, sender, receiver, nonce, transaction.data, transaction.id, int(time.time())) processed_txids.add(transaction.txid) break except: pass time.sleep(1) transaction_id += 20 time.sleep(0.1)
def addr_to_vk(addr): ''' Convert an address back into a verifying key format so you can verify a signature. ''' return VerifyingKey.from_string(base58.b58decode(bytes(addr, 'utf-8')))
def verify_vin(txid, index): txdump = dump_tx_ecdsa(txid, index) #i, pub, txid, s, r, x, z # | | \--- hash # | \------ pub decoded? # \---------------------- pub orig? import pprint pprint.pprint(txdump) print txdump['z'].decode("hex") print int(txdump['z'],16) def fix_pubkey(p): if p.startswith("04"): return p[2:] return p txdump['pub'] = fix_pubkey(txdump['pub']) #vk = VerifyingKey.from_public_point(int(txdump['x'],16),curve=curve) #vk = VerifyingKey.from_string(txdump['pub'], curve=curve) #print vk #logger.debug("verify --> %s " % (vk.pubkey.verifies(int(digest.encode("hex"), 16), Signature(sig[0], sig[1])))) # get raw transaction (txid) <-- vin[0]: scriptSig rpc = BtcRpc("http://*****:*****@127.0.0.1:8332") rawtx = rpc.rpc.getrawtransaction(txid) jsontxverbose = rpc.rpc.getrawtransaction(txid,1) #pprint.pprint(jsontxverbose) jsontx = pybitcointools.deserialize(rawtx) pprint.pprint(jsontx) scriptSigasm = jsontxverbose['vin'][index]['scriptSig']['asm'] logger.debug(scriptSigasm) scriptSig = jsontx['ins'][index]['script'] sigpubdecoded = asn1der.decode(scriptSig.decode("hex")[1:]) # skip first push sig = long(sigpubdecoded[0][0]), long(sigpubdecoded[0][1]) pubkey = sigpubdecoded[1] sighash_type = pubkey[0] logger.debug("sighash type: %r" % sighash_type) push = pubkey[1] btc_pubkey_type = pubkey[2] pubkey = pubkey[3:] logger.debug("r %s s %s"%(hex(sig[0]),hex(sig[1]))) logger.debug("pubkey: %r"%pubkey.encode("hex")) logger.debug("txdump: %r"%txdump['pub']) ''' # generate signdata # replace input script with funding script of 17SkEw2md5avVNyYgj6RiXuQKNwkXaxFyQ for txin in jsontx['ins']: txin['script']='' funding_txid = jsontxverbose['vin'][index]['txid'] funding_tx = rpc.rpc.getrawtransaction(funding_txid,1) #pprint.pprint(funding_tx) funding_script = funding_tx['vout'][0]['scriptPubKey']['hex'] jsontx['ins'][index]['script']=funding_script signdata= pybitcointools.serialize(jsontx) + "01000000" #SIGHASH ALL import hashlib digest = hashlib.sha256(hashlib.sha256(signdata.decode("hex")).digest()).digest() logger.debug(digest[::-1].encode("hex")) pause("--->") ''' pause("create verifying key...") vk = VerifyingKey.from_string(txdump['pub'].decode("hex"), curve=curve) digest = txdump['z'] print repr(pubkey) print repr(txdump['pub']) z = int(digest.decode("hex"),16) verifies = vk.pubkey.verifies(z,Signature(sig[0],sig[1])) logger.debug("verify --> %s "%(verifies)) if not verifies: pause("--verify false!--",critical=True) #print vk.verify_digest(scriptSigasm.split("[ALL]",1)[0].decode("hex"), digest, sigdecode=ecdsa.util.sigdecode_der) return BTCSignature(sig=Signature(sig[0],sig[1]), h=z, pubkey=pubkey, )
def decode(pr: str) -> Invoice: """bolt11 decoder, based on https://github.com/rustyrussell/lightning-payencode/blob/master/lnaddr.py """ hrp, decoded_data = bech32_decode(pr) if hrp is None or decoded_data is None: raise ValueError("Bad bech32 checksum") if not hrp.startswith("ln"): raise ValueError("Does not start with ln") bitarray = _u5_to_bitarray(decoded_data) # final signature 65 bytes, split it off. if len(bitarray) < 65 * 8: raise ValueError("Too short to contain signature") # extract the signature signature = bitarray[-65 * 8 :].tobytes() # the tagged fields as a bitstream data = bitstring.ConstBitStream(bitarray[: -65 * 8]) # build the invoice object invoice = Invoice() # decode the amount from the hrp m = re.search("[^\d]+", hrp[2:]) if m: amountstr = hrp[2 + m.end() :] if amountstr != "": invoice.amount_msat = _unshorten_amount(amountstr) # pull out date invoice.date = data.read(35).uint while data.pos != data.len: tag, tagdata, data = _pull_tagged(data) data_length = len(tagdata) / 5 if tag == "d": invoice.description = _trim_to_bytes(tagdata).decode("utf-8") elif tag == "h" and data_length == 52: invoice.description_hash = _trim_to_bytes(tagdata).hex() elif tag == "p" and data_length == 52: invoice.payment_hash = _trim_to_bytes(tagdata).hex() elif tag == "x": invoice.expiry = tagdata.uint elif tag == "n": invoice.payee = _trim_to_bytes(tagdata).hex() # this won't work in most cases, we must extract the payee # from the signature elif tag == "s": invoice.secret = _trim_to_bytes(tagdata).hex() elif tag == "r": s = bitstring.ConstBitStream(tagdata) while s.pos + 264 + 64 + 32 + 32 + 16 < s.len: route = Route( pubkey=s.read(264).tobytes().hex(), short_channel_id=_readable_scid(s.read(64).intbe), base_fee_msat=s.read(32).intbe, ppm_fee=s.read(32).intbe, cltv=s.read(16).intbe, ) invoice.route_hints.append(route) # BOLT #11: # A reader MUST check that the `signature` is valid (see the `n` tagged # field specified below). # A reader MUST use the `n` field to validate the signature instead of # performing signature recovery if a valid `n` field is provided. message = bytearray([ord(c) for c in hrp]) + data.tobytes() sig = signature[0:64] if invoice.payee: key = VerifyingKey.from_string(unhexlify(invoice.payee), curve=SECP256k1) key.verify(sig, message, hashlib.sha256, sigdecode=sigdecode_string) else: keys = VerifyingKey.from_public_key_recovery( sig, message, SECP256k1, hashlib.sha256 ) signaling_byte = signature[64] key = keys[int(signaling_byte)] invoice.payee = key.to_string("compressed").hex() return invoice
def kirk11(pubkey, sig, data): vk = VerifyingKey.from_string(pubkey, curve=_kirk11_curve()) vk.verify(sig, data)
def verify_message(self): vk = VerifyingKey.from_string(bytearray.fromhex(self.voter_address)) return vk.verify(bytearray.fromhex(self.signature), self.raw_vote.encode("utf-8"))
def onMessage(self, payload, isBinary): data = {} print("onmessage") allify = {} if isBinary: print("Binary message received: {0} bytes".format(len(payload))) else: payloaded = json.loads(payload.decode('utf-8')) print(payloaded["host"]) if str(payloaded["host"]) == str(ip): print("bu zaten sensin") else: payloaded = json.loads(payload.decode('utf-8')) if 'sender' in payloaded: data['sender'] = str(payloaded["sender"]) #1 data['receiver'] = str(payloaded["receiver"]) #2 data['previous_hash'] = str(transaction.objects.all().last().blockhash) #3 data['amount'] = str(payloaded["amount"]) #4 data['timestamp'] = str(payloaded["timestamp"]) #5 data["nonce"] = str(payloaded["nonce"]) data = collections.OrderedDict(sorted(data.items())) datashash = hashlib.sha256(json.dumps(data).encode('utf-8')).hexdigest() sig = json.loads(payloaded["P2PKH"]) print("datahashhere", datashash.encode('utf-8')) print("sigbyte is here", sig) print("sende weas here", payloaded["sender"]) wllt = generate_wallet_from_pkey(payloaded["sender"]) 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") data["response"] = "bad signature" return False 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() data["response"] = "Everything works correctly." return True else: print("other message") BroadcastServerFactory.broadcast(payload)
def from_string(cls, string): return cls(VerifyingKey.from_string(string, curve=SECP256k1))
def decode_public_key(public_key_string: str) -> PublicKey: """ Base58 String -> PublicKey """ hex_key = bytes.fromhex(decode(public_key_string)) return PublicKey.from_string(hex_key, curve=curve)
def verificarAssinatura(self, dados, assinatura, chavePublica): _vk = VerifyingKey.from_string(chavePublica) return _vk.verify(assinatura, dados.encode())