def separate_registration(): primary_authnr = Authenticator() backup_authnr = Authenticator() # Create a credential with the primary authenticator challenge = os.urandom(32) pub, cred, sig = primary_authnr.make_credential(challenge) assert ecdsa.verify(sig, challenge, pub) standard_creds = [cred] # Authenticate with the primary authenticator challenge = os.urandom(32) cred, sig = primary_authnr.get_assertion(challenge, standard_creds) assert ecdsa.verify(sig, challenge, pub) assert cred in standard_creds # Transfer recovery seed from backup authenticator to primary primary_authnr.import_recovery_seed( backup_authnr.export_recovery_seed()) # Create a backup public key with the primary authenticator aux = os.urandom(32) backup_creds = primary_authnr.derivepk_all(aux) backup_pub, backup_cred = backup_creds[0] # Perform recovery registration with backup authenticator challenge = os.urandom(32) chosen_cred, sig = backup_authnr.derivesk_authenticate( challenge, [backup_cred]) assert ecdsa.verify(sig, challenge, backup_pub) assert chosen_cred == backup_cred assert chosen_cred[1] == aux
def simultaneous_registration(): primary_authnr = Authenticator() backup_authnr = Authenticator() # Transfer recovery seed from backup authenticator to primary primary_authnr.import_recovery_seed( backup_authnr.export_recovery_seed()) # Create a credential and backup public key with the primary authenticator challenge = os.urandom(32) aux = os.urandom(32) pub, cred, sig, backup_creds = primary_authnr.make_credential_derivepk( challenge, aux) signed_data = challenge for c in backup_creds: signed_data += encode_pub(c[0]) assert ecdsa.verify(sig, signed_data, pub) standard_creds = [cred] backup_pub, backup_cred = backup_creds[0] # Authenticate with the primary authenticator challenge = os.urandom(32) cred, sig = primary_authnr.get_assertion(challenge, standard_creds) assert ecdsa.verify(sig, challenge, pub) assert cred in standard_creds # Perform recovery registration with backup authenticator challenge = os.urandom(32) chosen_cred, sig = backup_authnr.derivesk_authenticate( challenge, [backup_cred]) assert ecdsa.verify(sig, challenge, backup_pub) assert chosen_cred == backup_cred assert chosen_cred[1] == aux
def recordTimeECC(sizes, message): """ This function documents the times taken to generate the key, encrypt, and decrypt using the ECC cryptosystem Inputs: sizes: ECC key sizes message: message to encrypt Outputs: keyTime, encryptTime, decryptTime: times taken to do task """ keyTime, encryptTime, decryptTime = [], [], [] for size in sizes: print("Starting Size: ", size) startK = time.time() priv_key, pub_key = keys.gen_keypair(size) endK = time.time() keyTime.append((endK - startK)) startE = time.time() (r, s) = ecdsa.sign(message, priv_key, size) endE = time.time() encryptTime.append((endE - startE)) startD = time.time() ecdsa.verify((r, s), message, pub_key, size) endD = time.time() decryptTime.append((endD - startD)) return keyTime, encryptTime, decryptTime
def test_ecdsa_P256_verify(self): Q = Point( 0x8101ece47464a6ead70cf69a6e2bd3d88691a3262d22cba4f7635eaff26680a8, 0xd8a12ba61d599235f67d9cb4d58f1783d3ca43e78f0a5abaa624079936c0c3a9, curve=P256) msg = 'This is only a test message. It is 48 bytes long' sig = ( 0x7214bc9647160bbd39ff2f80533f5dc6ddd70ddf86bb815661e805d5d4e6f27c, 0x7d1ff961980f961bdaa3233b6209f4013317d3e3f9e1493592dbeaa1af2bc367) self.assertTrue(verify(sig, msg, Q, curve=P256, hashfunc=sha256)) sig = ( 0x7214bc9647160bbd39ff2f80533f5dc6ddd70ddf86bb815661e805d5d4e6fbad, 0x7d1ff961980f961bdaa3233b6209f4013317d3e3f9e1493592dbeaa1af2bc367) self.assertFalse(verify(sig, msg, Q, curve=P256, hashfunc=sha256))
def fast_ecdsa(count, loop): private_key = keys.gen_private_key(curve.P256) public_key = keys.get_public_key(private_key, curve.P256) # standard signature, returns two integers with open("message.txt", "rb") as f: m = f.read() time_list_sign = [] for l in range(loop): start = time.time() for c in range(count): r, s = ecdsa.sign(m, private_key) end = time.time() - start # print("["+str(l)+"th fast_ecdsa:sign second is "+ str(end) + "/"+str(count)+" signature") time_list_sign.append(end) ave_sign = numpy.mean(numpy.array(time_list_sign)) time_list_vrfy = [] for l in range(loop): start = time.time() for c in range(count): valid = ecdsa.verify((r, s), m, public_key) end = time.time() - start # print("["+str(l)+"th fast_ecdsa:vrfy second is "+ str(end) + "/"+str(count)+" signature") time_list_vrfy.append(end) ave_vrfy = numpy.mean(numpy.array(time_list_vrfy)) print("fast_ecdsa:sign average second is " + str(ave_sign) + "/" + str(count) + " signature") print("fast_ecdsa:vrfy average second is " + str(ave_vrfy) + "/" + str(count) + " signature") return time_list_sign, time_list_vrfy
def verifyVote(self, privateKey): if (self.signature == "" or len(self.signature) == 0): return False r, s = ecdsa.sign(self.voteHash, privateKey, curve=curve.secp256k1, hashfunc=hl.sha256) decoded_r, decoded_s = DEREncoder.decode_signature(self.signature) # Se os parâmetros são diferentes, a assinatura é inválida if (r != decoded_r or s != decoded_s): return False # Verifica a assinatura valid = ecdsa.verify((r, s), self.voteHash, self.voter, curve=curve.secp256k1, hashfunc=hl.sha256) if (not valid): return False return True
def validate_signature(msg, sig, pubkey): key_type, key_string = signature_from_string(sig) key = check_decode(key_string, key_type) r,s,i = signature_from_buffer(key) pub_key_point = point_decode_from(ecdsa_curve.secp256k1, check_decode(pubkey[3:])) res = ecdsa.verify((r, s), msg, pub_key_point, ecdsa_curve.secp256k1) return res
def verify(message, pub_key, signature): signature_length = len(signature) half = signature_length // 2 r = int(signature[:half], 16) s = int(signature[half:], 16) valid = ecdsa.verify((r, s), message, pub_key, curve=curve.secp256k1) return valid
def did_callback_elaphant(request): if request.method == 'POST': response = json.loads(request.body) if request.content_type == "application/json" or 'Data' not in response.keys( ): HttpResponse(status=400) data = json.loads(response['Data']) sig = response['Sign'] client_public_key = data['PublicKey'] r, s = int(sig[:64], 16), int(sig[64:], 16) public_key = SEC1Encoder.decode_public_key( unhexlify(client_public_key), curve.P256) valid = ecdsa.verify((r, s), response['Data'], public_key) if not valid: return JsonResponse({'message': 'Unauthorized'}, status=401) try: recently_created_time = timezone.now() - timedelta(minutes=1) did_request_query_result = DIDRequest.objects.get( state=data["RandomNumber"], created_at__gte=recently_created_time) if not did_request_query_result: return JsonResponse({'message': 'Unauthorized'}, status=401) data["auth"] = True DIDRequest.objects.filter(state=data["RandomNumber"]).update( data=json.dumps(data)) except Exception as e: logging.debug(f"Method: did_callback_elaphant Error: {e}") return JsonResponse({'error': str(e)}, status=404) return JsonResponse({'result': True}, status=200)
def proof_of_work(self, mysql): #Start by verifying all the transactions in the pool verified_transactions = [] cur = mysql.connection.cursor() result = cur.execute("SELECT * FROM blockchain_transactions") transactions = cur.fetchall() #We are going to verify all the transactions in the pool before we add them to the block ..... #then clear the transaction pool by deleting all the transactions in the database .... if result > 0: for transaction in transactions: id = transaction['id'] data = json.loads(transaction['transaction']) signature_string = transaction['signature'] string_transaction = json.dumps(data, sort_keys = True).encode() signature = eval(signature_string) public, key2 = keys.get_public_keys_from_sig(signature, string_transaction, curve=curve.secp256k1, hashfunc=ecdsa.sha256) is_valid = ecdsa.verify(signature, string_transaction, public, curve.secp256k1, ecdsa.sha256) if is_valid is True: verified_transactions.append(data) cur.execute("DELETE from blockchain_transactions WHERE id=%s", [id]) mysql.connection.commit() #Now we add the transactions to the new block the_time = datetime.now() prev_hash = ''
def verify(pub_key, data, signature, hashfunc=sha256, curve=curve.P256, sign_fmt='DER', sign_size=32, pub_key_fmt='RAW'): if pub_key_fmt == 'RAW': pub_key_encoded = pub_key.encode() elif pub_key_fmt == '04': pub_key_encoded = pub_key[2:].encode() else: raise UnknownPublicKeyFormatError("fmt: '%s'" % sign_fmt) x, y = split_str_to_halves(pub_key_encoded) x, y = int(x, 16), int(y, 16) pub_key_point = Point(x, y, curve=curve) if sign_fmt in ['RAW', 'DER']: r, s = decode_sig(bytes.fromhex(signature), fmt=sign_fmt) else: raise UnknownSignatureFormatError("fmt: '%s'" % sign_fmt) priv_key = keys.gen_private_key(curve) valid = ecdsa.verify((r, s), data, pub_key_point, curve=curve, hashfunc=hashfunc) return valid
def handle_ecdh(self, body): self.ecdh_blob = body key, signature = body[:0x90], body[0x90:] x = key[0x8:0x8+0x20] y = key[0x4c:0x4c+0x20] x, y = [int(hexlify(i[::-1]), 0x10) for i in [x, y]] if not P256.is_point_on_curve( (x, y) ): raise Exception('Point is not on the curve') self.ecdh_q = Point(x, y, P256) self.trace('ECDH params:') self.trace('x=0x%x' % x) self.trace('y=0x%x' % y) l, signature = signature[:4], signature[4:] l, = unpack('<L', l) signature, zeroes = signature[:l], signature[l:] if zeroes != b'\0'*len(zeroes): raise Exception('Zeroes expected') # The following pub key is hardcoded for each fw revision in the synaWudfBioUsb.dll. # Corresponding private key should only be known to a genuine Synaptic device. fwpub=Point( 0xf727653b4e16ce0665a6894d7f3a30d7d0a0be310d1292a743671fdf69f6a8d3, 0xa85538f8b6bec50d6eef8bd5f4d07a886243c58b2393948df761a84721a6ca94, P256) signature=DEREncoder().decode_signature(signature) if not verify(signature, key, fwpub): raise Exception('Untrusted device')
def verify(transaction: str, signature: str, public_key: str) -> bool: r, s = json.loads(signature) public_key = decode_public_key(public_key) return ecdsa.verify((r, s), transaction, public_key, curve=curve.secp256k1)
def verify_signature(self): """verify an elliptic curves signature on a ballot""" if self.signature: return ecdsa.verify(self.signature, self.string_for_hashing(), self.voter.public_key) else: return False
def checkNonce(file, m, r, s): _, public_key = keys.import_key(file) print("public key: ", public_key) # should return True as the signature we just generated is valid. valid = ecdsa.verify((r, s), m, public_key) print("Is it valid? = ", valid) return valid
def verify(self): x, y = DEREncoder.decode_signature(base64.b64decode(self.sender)) public_key = Point(x, y, Transaction._curve) r, s = DEREncoder.decode_signature(base64.b64decode(self.signature)) return ecdsa.verify((r, s), self.data, public_key, curve=Transaction._curve)
def is_sig_valid(signature: str, pub_key: str, msg: str) -> bool: ''' Given a signature, public key, and a message, check if the signature is valid ''' r, s = signature.split('x') p = pub_key_to_point(pub_key) return ecdsa.verify((int(r, 16), int(s, 16)), msg, p)
def validate_tx(self, tx, public_key): """ validates a single transaction :param tx = { "sender" : User.address, ## a list of locations of previous transactions ## look at "locations" : [{"block":block_num, "tx":tx_num, "amount":amount}, ...], "receivers" : {account:amount, account:amount, ...} } :param public_key: User.public_key :return: if tx is valid return tx """ is_correct_hash = False base_tx = { "sender": tx["sender"], "location": tx["location"], "receivers": tx["receivers"], } if self.hash(base_tx) == tx["hash"]: is_correct_hash = True is_signed = ecdsa.verify(tx["signature"], tx["hash"], public_key, curve=curve.secp256k1) blockIndex = tx["location"]["block"] txIndex = tx["location"]["tx"] # what is the meaning of isFunded? is_funded = False list_of_transactions = self.chain[blockIndex]["transactions"] amount = 0 if tx["sender"] in list_of_transactions[txIndex]["receivers"]: amount = list_of_transactions[txIndex]["receivers"][tx["sender"]] if amount >= 0: is_funded = True is_all_spent = False totalAmountSpent = 0 for rec in tx["receivers"].keys(): totalAmountSpent += tx["receivers"][rec] is_all_spent = True if totalAmountSpent == amount else False consumed_previous = False # for each block after blockIndex , need to verify if blockIndex and tx is not used as location for block in self.chain[blockIndex:]: for transaction in block["transactions"]: if transaction["sender"] == tx["sender"]: if transaction["location"]["block"] == blockIndex and transaction["location"]["tx"] == txIndex: consumed_previous = True if (is_correct_hash and is_signed and is_funded and is_all_spent and not consumed_previous): return tx else: return None
def check_signature(r, s, pk_string, data): n_r = int(r) n_s = int(s) pk = pk_string.split('\n') x = pk[0].split()[1] y = pk[1].split()[1] S = Point(int(x, 0), int(y, 0), curve=P256) valid = ecdsa.verify((n_r, n_s), data, S) return valid
def check_signature(self): if self._from == NULL_BYTE: return True if not self.is_signed(): return False to_sign = self.calculate_hash() return ecdsa.verify( self._signature, to_sign, SEC1Encoder.decode_public_key(self._from, curve=curve.P256))
def is_valid(self): if self.signature is None: return True if len(self.signature) == 0 and self.to_address is None: return False hash_tx = self.calculate_hash() pubkey = keys.get_public_keys_from_sig(self.signature, hash_tx, curve=curve.P256, hashfunc=sha256) valid = ecdsa.verify(self.signature, hash_tx, pubkey[0], hashfunc=sha256) return valid
def is_signature_valid(self, transactions): if self.sender == '0': return True else: sigR, sigS = map(int, self.signature.split()) senderX, senderY = map(int, self.sender.address.split()) sender_transactions = len(transactions) msg_signed = f'{self.sender.address} {self.recipient.address} {self.message} {self.amount} {sender_transactions}' return ecdsa.verify((sigR, sigS), msg_signed, (senderX, senderY))
def test_ecdsa_P256_SHA512_sign(self): d = 0xC9AFA9D845BA75166B5C215767B1D6934E50C3DB36E89B127B8A622B120F6721 expected = ( 0x8496A60B5E9B47C825488827E0495B0E3FA109EC4568FD3F8D1097678EB97F00, 0x2362AB1ADBE2B8ADF9CB9EDAB740EA6049C028114F2460F96554F61FAE3302FE) sig = sign('sample', d, curve=P256, hashfunc=sha512) self.assertEqual(sig, expected) Q = d * P256.G self.assertTrue(verify(sig, 'sample', Q, curve=P256, hashfunc=sha512))
def verifydata(cls, pub=None, verkey=None, sigdata=None, origdata=None): assert sigdata is not None, "no signed data given!" assert origdata is not None, "no original data given!" if pub is not None: verkey = cls.pub2vkey(pub) sigdata = binascii.unhexlify(sigdata) order = 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE BAAEDCE6 AF48A03B BFD25E8C D0364141' r, s = ecdsa.util.sigdecode_der(sigdata, order) return fecdsa.verify((r, s), origdata, verkey, fcurve.secp256k1)
def __validate_fastecdsa_signature(self, verification_string, signature, charset): """Return True if signature is valid, using FastEDSA algorithms.""" ecdsa_public_key = PEMEncoder.decode_public_key( self.inflated_public_key) # signature_length = len(signature) r, s = DEREncoder.decode_signature(signature) # r_bytes, s_bytes = signature[:signature_length // 2], signature[signature_length // 2:signature_length] # r, s = int.from_bytes(r_bytes, 'big', signed=False), int.from_bytes(s_bytes, 'big', signed=False) signing_algorithm = self.signing_algorithm.upper() if ('SHA-' in signing_algorithm): signing_algorithm = signing_algorithm.replace('SHA-', 'SHA') if ('P-' in signing_algorithm): signing_algorithm = signing_algorithm.replace('P-', 'P') if signing_algorithm == self.SIGNING_ALGORITHM_ECDSA_P256: curve_algorithm = curve.P256 elif signing_algorithm == self.SIGNING_ALGORITHM_ECDSA_P384: curve_algorithm = curve.P384 elif signing_algorithm == self.SIGNING_ALGORITHM_ECDSA_P521: curve_algorithm = curve.P2521 elif signing_algorithm == self.SIGNING_ALGORITHM_ECDSA_CURVE25519: curve_algorithm = curve.W25519 else: raise UnsupportedAlgorithmException(self.signing_algorithm) hashing_algorithm = self.hashing_algorithm.upper().replace('-', '') if hashing_algorithm == self.HASHING_ALGORITHM_SHA256: hash_function = hashlib.sha256 elif hashing_algorithm == self.HASHING_ALGORITHM_SHA512: hash_function = hashlib.sha512 else: raise UnsupportedAlgorithmException(self.hashing_algorithm) is_valid = False try: ecdsa.verify((r, s), signature, ecdsa_public_key, curve=curve_algorithm, hashfunc=hash_function) is_valid = True except ecdsa.EcdsaError: is_valid = False return is_valid
def digital_signature(curve, message): sk, pk = keys.gen_keypair(curve) # hash message and sign r, s = ecdsa.sign(message, sk, hashfunc=sha256) # verify signature valid = ecdsa.verify((r, s), message, pk, hashfunc=sha256) return valid
def test_ecdsa_P256_SHA384_sign(self): d = 0xC9AFA9D845BA75166B5C215767B1D6934E50C3DB36E89B127B8A622B120F6721 expected = ( 0x0EAFEA039B20E9B42309FB1D89E213057CBF973DC0CFC8F129EDDDC800EF7719, 0x4861F0491E6998B9455193E34E7B0D284DDD7149A74B95B9261F13ABDE940954) sig = sign('sample', d, curve=P256, hashfunc=sha384) self.assertEqual(sig, expected) Q = d * P256.G self.assertTrue(verify(sig, 'sample', Q, curve=P256, hashfunc=sha384))
def test_ecdsa_P256_SHA224_sign(self): d = 0xC9AFA9D845BA75166B5C215767B1D6934E50C3DB36E89B127B8A622B120F6721 expected = ( 0x53B2FFF5D1752B2C689DF257C04C40A587FABABB3F6FC2702F1343AF7CA9AA3F, 0xB9AFB64FDC03DC1A131C7D2386D11E349F070AA432A4ACC918BEA988BF75C74C) sig = sign('sample', d, curve=P256, hashfunc=sha224) self.assertEqual(sig, expected) Q = d * P256.G self.assertTrue(verify(sig, 'sample', Q, curve=P256, hashfunc=sha224))
def test_ecdsa_P256_SHA2_sign(self): d = 0xC9AFA9D845BA75166B5C215767B1D6934E50C3DB36E89B127B8A622B120F6721 expected = ( 0xEFD48B2AACB6A8FD1140DD9CD45E81D69D2C877B56AAF991C34D0EA84EAF3716, 0xF7CB1C942D657C41D436C7A1B6E29F65F3E900DBB9AFF4064DC4AB2F843ACDA8) sig = sign('sample', d, curve=P256, hashfunc=sha256) self.assertEqual(sig, expected) Q = d * P256.G self.assertTrue(verify(sig, 'sample', Q, curve=P256, hashfunc=sha256))
def test_ecdsa_P256_SHA1_sign(self): d = 0xC9AFA9D845BA75166B5C215767B1D6934E50C3DB36E89B127B8A622B120F6721 expected = ( 0x61340C88C3AAEBEB4F6D667F672CA9759A6CCAA9FA8811313039EE4A35471D32, 0x6D7F147DAC089441BB2E2FE8F7A3FA264B9C475098FDCF6E00D7C996E1B8B7EB, ) sig = sign('sample', d, curve=P256, hashfunc=sha1) self.assertEqual(sig, expected) Q = d * P256.G self.assertTrue(verify(sig, 'sample', Q, curve=P256, hashfunc=sha1))