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 convert_der_sig(signature, as_hex=True): """ Extract content from DER encoded string: Convert DER encoded signature to signature string. :param signature: DER signature :type signature: bytes :param as_hex: Output as hexstring :type as_hex: bool :return bytes, str: Signature """ if not signature: return "" if USE_FASTECDSA: r, s = DEREncoder.decode_signature(bytes(signature)) else: sg, junk = ecdsa.der.remove_sequence(signature) if junk != b'': raise EncodingError("Junk found in encoding sequence %s" % junk) r, sg = ecdsa.der.remove_integer(sg) s, sg = ecdsa.der.remove_integer(sg) sig = '%064x%064x' % (r, s) if as_hex: return sig else: return binascii.unhexlify(sig)
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 test_encode_decode_all_curves(self): for curve in CURVES: d = randint(1, curve.q) Q = d * curve.G r, s = sign("sign me", d, curve=curve) encoded = DEREncoder.encode_signature(r, s) decoded_r, decoded_s = DEREncoder.decode_signature(encoded) self.assertEqual(decoded_r, r) self.assertEqual(decoded_s, s)
def verify( verifying_key: VerifyingKey, message_digest_bytes: bytes, signature_bytes: bytes, ) -> bool: r, s = DEREncoder.decode_signature(signature_bytes) return ecdsa.verify( (r, s), message_digest_bytes, verifying_key, curve=curve.secp256k1, hashfunc=IdentityHash, )
def _test_runner(self, tests, curve, hashfunc): for test_group in tests: keybytes = unhexlify(test_group["key"]["uncompressed"]) public_key = SEC1Encoder.decode_public_key(keybytes, curve) for test in test_group["tests"]: try: message = unhexlify(test["msg"]) sigbytes = unhexlify(test["sig"]) signature = DEREncoder.decode_signature(sigbytes) expected = test["result"] == "valid" result = verify(signature, message, public_key, curve, hashfunc) self.assertEqual(result, expected, test) except: self.assertFalse(test["result"] == "valid", test)
def verify_correctness(): clientDataJSON_hash = os.urandom(32) primary_authnr = Authenticator() backup_authnr = Authenticator() # Create a credential with the primary authenticator basic_make_credential(primary_authnr, clientDataJSON_hash) allowList = [{ 'type': 'public-key', 'id': i } for i in primary_authnr._credentials.keys()] # Transfer recovery seed from backup authenticator to primary primary_authnr.import_recovery_seed(backup_authnr.export_recovery_seed([0 ])) # Generate a recovery credential with the primary authenticator recovery_creds = ctap2.AuthenticatorData( cbor.decode( generate_backups_get_assertion( primary_authnr, clientDataJSON_hash, allowList))[2]).extensions['recovery']['creds'] recovery_pubkey = cose_key_to_point( ctap2.AttestedCredentialData(recovery_creds[0]).public_key) recovery_allowCredentials = [{ 'id': ctap2.AttestedCredentialData(cred).credential_id, 'type': 'public-key' } for cred in recovery_creds] # Perform recovery registration with backup authenticator attObj_bytes = recovery_make_credential(backup_authnr, clientDataJSON_hash, recovery_allowCredentials) att_obj = ctap2.AttestationObject(attObj_bytes) # Verify that backup authenticator returns the correct recovery credential ID recovery_cred_id = att_obj.auth_data.extensions['recovery']['credId'] assert recovery_cred_id == ctap2.AttestedCredentialData( recovery_creds[0]).credential_id # Verify that backup authenticator returns a valid recovery signature auth_data_without_extensions = att_obj.auth_data[:37 + len(att_obj.auth_data. credential_data)] recovery_sig = att_obj.auth_data.extensions['recovery']['sig'] assert ecdsa.verify(DEREncoder.decode_signature(recovery_sig), auth_data_without_extensions + clientDataJSON_hash, recovery_pubkey)
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 makecredential_process_recovery_extension( self, authData, clientDataHash, extension_output, ): action = extension_output['action'] if action == 'state': pass elif action == 'recover': authData_without_extensions = authData pubkey_cose = self._recovery_credentials[ extension_output['credId'] ].public_key pubkey = cose_key_to_point(pubkey_cose) assert ecdsa.verify( DEREncoder.decode_signature(extension_output['sig']), authData_without_extensions + clientDataHash, pubkey, hashfunc=hashlib.sha256 ) else: raise UnknownAction()
def test_decode_signature(self): with self.assertRaises(InvalidDerSignature): DEREncoder.decode_signature(b"") # length too short with self.assertRaises(InvalidDerSignature): DEREncoder.decode_signature( b"\x31\x06\x02\x01\x01\x02\x01\x02") # invalid SEQUENCE marker with self.assertRaises(InvalidDerSignature): DEREncoder.decode_signature(b"\x30\x07\x02\x01\x01\x02\x01\x02" ) # invalid length (too short) with self.assertRaises(InvalidDerSignature): DEREncoder.decode_signature(b"\x30\x05\x02\x01\x01\x02\x01\x02" ) # invalid length (too long) with self.assertRaises(InvalidDerSignature): DEREncoder.decode_signature( b"\x30\x06\x02\x03\x01\x02\x01\x02") # invalid length of r with self.assertRaises(InvalidDerSignature): DEREncoder.decode_signature( b"\x30\x06\x02\x01\x01\x02\x03\x02") # invalid length of s with self.assertRaises(InvalidDerSignature): DEREncoder.decode_signature(b"\x30\x06\x03\x01\x01\x02\x01\x02" ) # invalid INTEGER marker for r with self.assertRaises(InvalidDerSignature): DEREncoder.decode_signature( b"\x30\x06\x02\x00\x02\x01\x02") # length of r is 0 with self.assertRaises(InvalidDerSignature): DEREncoder.decode_signature( b"\x30\x06\x02\x01\x81\x02\x01\x02") # value of r is negative with self.assertRaises(InvalidDerSignature): DEREncoder.decode_signature(b"\x30\x07\x02\x02\x00\x01\x02\x01\x02" ) # value of r starts with a zero byte with self.assertRaises(InvalidDerSignature): DEREncoder.decode_signature(b"\x30\x06\x02\x01\x01\x03\x01\x02" ) # invalid INTEGER marker for s with self.assertRaises(InvalidDerSignature): DEREncoder.decode_signature( b"\x30\x06\x02\x01\x01\x02\x00") # value of s is 0 with self.assertRaises(InvalidDerSignature): DEREncoder.decode_signature( b"\x30\x06\x02\x01\x01\x02\x01\x81") # value of s is negative with self.assertRaises(InvalidDerSignature): DEREncoder.decode_signature(b"\x30\x07\x02\x01\x01\x02\x02\x00\x02" ) # value of s starts with a zero byte self.assertEqual( DEREncoder.decode_signature(b"\x30\x06\x02\x01\x01\x02\x01\x02"), (1, 2)) self.assertEqual( DEREncoder.decode_signature( b"0\x08\x02\x02\x00\x80\x02\x02\x00\x80"), (128, 128)) # verify zero bytes self.assertEqual( DEREncoder.decode_signature( b"0\x08\x02\x02\x03\xE8\x02\x02\x03\xE8"), (1000, 1000)) # verify byte order
def verify(signature, message_bytes: str, public_key: Point): r, s = DEREncoder.decode_signature(bytes.fromhex(signature)) return ecdsa.verify((r, s), message_bytes, public_key, curve=public_key.curve)