def test_loopback(self): hashed_msg = SHA512.new(b("test")) signer = DSS.new(self.key_priv, 'fips-186-3') signature = signer.sign(hashed_msg) verifier = DSS.new(self.key_pub, 'fips-186-3') verifier.verify(hashed_msg, signature)
def test_loopback(self): hashed_msg = SHA512.new(b("test")) signer = DSS.new(self.key_priv, 'deterministic-rfc6979') signature = signer.sign(hashed_msg) verifier = DSS.new(self.key_pub, 'deterministic-rfc6979') verifier.verify(hashed_msg, signature)
def test_sign_verify(self): """Verify public/private method""" self.description = "can_sign() test" signer = DSS.new(self.key_priv, 'fips-186-3') self.failUnless(signer.can_sign()) signer = DSS.new(self.key_pub, 'fips-186-3') self.failIf(signer.can_sign())
def test_sign_verify(self): """Verify public/private method""" self.description = "can_sign() test" signer = DSS.new(self.key_priv, 'fips-186-3') self.assertTrue(signer.can_sign()) signer = DSS.new(self.key_pub, 'fips-186-3') self.assertFalse(signer.can_sign())
def _fips_sign(self, test_vectors): """Positive tests for signature generation""" for tv in test_vectors: self.description = tv.desc key = DSA.construct([tv.Y, tv.G, tv.P, tv.Q, tv.X], False) hash_obj = tv.hashmod.new(tv.Msg) signer = DSS.new(key, 'fips-186-3', randfunc=StrRNG(tv.K)) signature = signer.sign(hash_obj) self.assertEqual(signature, tv.Signature)
def comprobarECC_PSS(texto, firma, key_public): h = SHA256.new(texto.encode()) verifier = DSS.new(key_public, 'fips-186-3') try: verifier.verify(h, firma) print("The message is authentic.") return True except (ValueError, TypeError): print("The message is not authentic.") return False
def comprobarECC_PSS(texto, firma, key_public): h = SHA256.new(texto.encode("utf-8")) verifier = DSS.new(key_public, 'fips-186-3') try: verifier.verify(h, firma) print("Correcto") return True except (ValueError, TypeError): print("Incorrecto") return False
def _fips_verify_negative(self, test_vectors): """Negative tests for signature verification""" for tv in test_vectors: self.description = tv.desc key = DSA.construct([tv.Y, tv.G, tv.P, tv.Q], False) hash_obj = tv.hashmod.new(tv.Msg) signer = DSS.new(key, 'fips-186-3') self.assertRaises(ValueError, signer.verify, hash_obj, tv.Signature)
def verify_message(message): eccpubkey = ECC.import_key(message["eccpubkey"]) h = SHA256.new(message["aeskey"] + message["nonce"] + message["message"]) verifier = DSS.new(eccpubkey, 'fips-186-3') try: verifier.verify(h, message["signature"]) return True except ValueError: return False
def ecdsa_verify(msg, signature): publicKey = readPEM_ECC('pubkey_ecdsa.pem') print("public Key:", publicKey) sha = SHA.new(msg) verifier = DSS.new(publicKey, 'fips-186-3') try: verifier.verify(sha, signature) print('Authentic') except ValueError: print('Not Authentic')
def sign_transaction(self, private_key): # Sign a transaction using the private_key private_key = ECC.import_key(binascii.unhexlify(private_key)) signer = DSS.new(private_key, 'fips-186-3') #h = hashlib.sha256.new(str(self.odict_transaction()).encode('utf8')) h = SHA256.new(str(self.odict_transaction()).encode('utf8')) self.signature = binascii.hexlify(signer.sign(h)).decode('utf8') # When the signature is created the id can be set self.id = self.hash_transaction()
def test2(self): for sig in self.signatures: tk = sig.test_key key = DSA.construct([tk.y, tk.g, tk.p, tk.q, tk.x], False) signer = DSS.new(key, 'deterministic-rfc6979') hash_obj = sig.module.new(sig.message) result = signer.sign(hash_obj) self.assertEqual(sig.result, result)
def DSS_verify(signature, message, h): hash_obj = SHA256.new(message) pkey = DSS.new(publickey, 'fips-186-3') if h == hash_obj.hexdigest(): try: pkey.verify(hash_obj, signature) valid = True except ValueError: valid = False return valid
def test_negative_unapproved_hashes(self): """Verify that unapproved hashes are rejected""" from Crypto.Hash import SHA1 self.description = "Unapproved hash (SHA-1) test" hash_obj = SHA1.new() signer = DSS.new(self.key_priv, 'fips-186-3') self.assertRaises(ValueError, signer.sign, hash_obj) self.assertRaises(ValueError, signer.verify, hash_obj, b("\x00") * 40)
def varify_message(self, text, signature, key): pubKey = DSA.import_key(bytes(key, 'utf-8')) hash_obj = SHA256.new(bytes(text, 'utf-8')) verifier = DSS.new(pubKey, 'fips-186-3') signature = base64.b64decode(signature) try: verifier.verify(hash_obj, signature) return True except ValueError: return False
def create(request): if request.method == 'POST': voter_id = request.POST.get('voter-id-input') vote = request.POST.get('vote-input') private_key = request.POST.get('private-key-input') # Create ballot as string vector timestamp = datetime.datetime.now().timestamp() ballot = "{}|{}|{}".format(voter_id, vote, timestamp) print('\ncasted ballot: {}\n'.format(ballot)) signature = '' try: # Create signature priv_key = ECC.import_key(private_key) print(priv_key) h = SHA3_256.new(ballot.encode('utf-8')) signature = DSS.new(priv_key, 'fips-186-3').sign(h) print('\nsignature: {}\n'.format(signature.hex())) # Verify the signature using registered public key pub_key = ECC.import_key(settings.PUBLIC_KEY) print(pub_key) verifier = DSS.new(pub_key, 'fips-186-3') verifier.verify(h, signature) status = 'The ballot is signed successfully.' error = False except (ValueError, TypeError): status = 'The key is not registered.' error = True context = { 'ballot': ballot, 'signature': signature, 'status': status, 'error': error, } return render(request, 'ballot/status.html', context) context = { 'voter_id': uuid.uuid4(), } return render(request, 'ballot/create.html', context)
def present(self, nonce: bytes) -> (List[Cert], bytes): """ 자신이 발급받아온 cert chain을 통해 자신의 서명을 증명 :param nonce: 랜덤 값 :return: cert_chain, sign(nonce) """ signer = DSS.new(self.__secret, 'fips-186-3') hash_value = SHA256.new(nonce) sign = signer.sign(hash_value) return copy.deepcopy(self.cert), sign
def verify_transaction_signature(self, sender_address, signature, transaction): public_key = ECC.import_key(binascii.unhexlify(sender_address)) verifier = DSS.new(public_key, 'fips-186-3') h = SHA512.new(str(transaction).encode('utf-8')) try: verifier.verify(h, binascii.unhexlify(signature)) return True except ValueError: return False
def ecVerifySignatureFromBase64(publicKeyPem, message, signatureBase64): ecPublicKey = ECC.import_key(publicKeyPem) signatureBytes = base64Decoding(signatureBase64) hashMessage = SHA256.new(message.encode("ascii")) verifier = DSS.new(ecPublicKey, 'fips-186-3', 'der') try: verifier.verify(hashMessage, signatureBytes) return True except ValueError: return False
def verify(self, cert_chain: List[Cert], pub_key: bytes, nonce: bytes, sign: bytes): """ TODO: cert_chain을 검증하고 pub_key의 서명을 확인함 root issuer는 저장된 root ca에 대한 정보를 이용하여 확인 cert chain 검증 결과 root ca로부터 연결된 신뢰 관계를 갖고 있을 경우 True 반환 :param cert_chain: :param pub_key: :param nonce: :param sign: :return: """ # public key 체인 확인 pub = {self.root: True} for cert in cert_chain: if not pub.get(cert.issuer): return False public_key = ECC.import_key(cert.issuer) hash_value = SHA256.new(cert.public) verifier = DSS.new(public_key, 'fips-186-3') try: verifier.verify(hash_value, cert.sign) pub[cert.public] = True except: pass if not pub.get(pub_key): return False # sign 확인 public_key = ECC.import_key(pub_key) hash_value = SHA256.new(nonce) verifier = DSS.new(public_key, 'fips-186-3') try: verifier.verify(hash_value, sign) return True except: return False
def verifySignature(self, signature): data = self.sender + self.reciepient + self.domain hash_msg = SHA256.new(data.encode('utf8')) pub_key_for_vetifier = ECC.import_key(self.sender) verifier = DSS.new(pub_key_for_vetifier, 'fips-186-3') try: verifier.verify(hash_msg, signature) except ValueError: print('Signature verified error') else: print('Signature verified succeed')
def sign_with_provided_privkey(dict_of_privkey_numbers, message): """ :param dict_of_privkey_numbers: dictionary with numbers to recreate key {'x': large int, 'y': large int, 'd': large int} :param message: str or bytes :return: signature """ if not isinstance(message, (bytes, str)): return None elif isinstance(message, str): message = message.encode() key = None try: key = ECC.construct(curve="P-256", point_x=dict_of_privkey_numbers["x"], point_y=dict_of_privkey_numbers["y"], d=dict_of_privkey_numbers["d"]) except KeyError as e: # does not have all required ECC attributes x, y and d for private key con print(f"in digitalsigner.py: exception occured:\n{e}") except AttributeError as e: # x, y, d might are not ints. if isinstance(dict_of_privkey_numbers["x"], str): try: key = ECC.construct(curve="P-256", point_x=PKI.convert_dict_keys_to_int( dict_of_privkey_numbers["x"]), point_y=PKI.convert_dict_keys_to_int( dict_of_privkey_numbers["y"]), d=PKI.convert_dict_keys_to_int( dict_of_privkey_numbers["d"])) except Exception as e: print(f"in digitalsigner.py: exception occured:\n{e}") else: print(f"in digitalsigner.py: exception occured:\n{e}") except ValueError as e: # the numbers provided do not represent a valid point on ECC curve print(f"in digitalsigner.py: exception occured:\n{e}") if key is None: return None hash_of_message = SHA256.new(message) signer = DSS.new(key, mode="fips-186-3") digital_signature = signer.sign(hash_of_message) digital_signature = base64.b85encode(digital_signature).decode() return digital_signature
def verify(publicKey, signature, toSign): key = ECC.import_key(publicKey) h = SHA256.new(str(toSign).encode()) verifier = DSS.new(key, 'fips-186-3') try: verifier.verify(h, signature) print("The message is authentic.") return True except ValueError: print("The message is not authentic.") return False
def sign(self, message): # Create a new DSA key key = DSA.generate(1024) # Sign a message message = bytes(message.encode()) hash_obj = SHA256.new(message) signer = DSS.new(key, 'fips-186-3') start_time = timer() signature = signer.sign(hash_obj) self.executionTime = timer() - start_time return signature.hex().upper()
def sign_transaction(self, private_key): # Sign a transaction using the private_key # Note: Don't worry too much about the encoding/decoding stuff. # It's not necessary to understand this completely. private_key = ECC.import_key(binascii.unhexlify(private_key)) signer = DSS.new(private_key,'fips-186-3') h = SHA256.new(str(self.odict_transaction()).encode('utf8')) self.signature = binascii.hexlify(signer.sign(h)).decode('utf8') # When the signature is created the id can be set self.id = self.hash_transaction()
def test_verify(self, tv): self._id = "Wycheproof DSA Test #" + str(tv.id) hashed_msg = tv.hash_module.new(tv.msg) signer = DSS.new(tv.key, 'fips-186-3', encoding='der') try: signature = signer.verify(hashed_msg, tv.sig) except ValueError, e: if tv.warning: return assert not tv.valid
def verify(message, signature, public_key): # hash the message h = hash(message) # load the verification module verifier = DSS.new(public_key, 'deterministic-rfc6979') try: verifier.verify(h, signature) return True except ValueError: return False
def verify_signature(message, sig, pk): h = SHA256.new(message) key = ECC.import_key(pk) verifier = DSS.new(key, 'fips-186-3') try: verifier.verify(h, sig) print("Valid!") return True except ValueError: print("Invalid!") return False
def OP_CHECKSIG(self): key_pub = unhexlify(self.stack.pop()) sig = self.stack.pop() key = ECC.import_key(key_pub) h = SHA256.new(key_pub) verifier = DSS.new(key, 'fips-186-3') try: verifier.verify(h, sig) return True except ValueError: return False
def verify_message(pubkey, message: Union[bytes, List[pairing.pc_element]], signature: bytes) -> bool: if isinstance(message, list): message = trapdoor_to_bytes(message) h = SHA512.new(message) verifier = DSS.new(pubkey, 'fips-186-3') try: verifier.verify(h, signature) return True except ValueError: return False
def test4(self): """Verify that unapproved hashes are rejected""" from Crypto.Hash import RIPEMD160 self.description = "Unapproved hash (RIPEMD160) test" key = DSA.construct((self.Y, self.G, self.P, self.Q)) hash_obj = RIPEMD160.new() signer = DSS.new(key, 'fips-186-3') self.assertRaises(ValueError, signer.sign, hash_obj) self.assertRaises(ValueError, signer.verify, hash_obj, b("\x00") * 40)
def VerificaFirma(self, content: dict, pubkey): try: tmp = content['id'].encode('utf-8') + content['pubk'].encode( 'utf-8') h = SHA256.new(tmp) verifier = DSS.new(pubkey, 'deterministic-rfc6979') verifier.verify(h, b64decode(content['sig'])) return True except ValueError: print("FIRMA NON VALIDA") return False
def comprobarECC_PSS(texto, firma, key_public): hash = SHA256.new(texto) verificador = DSS.new(key_public, "fips-186-3") try: verificador.verify(hash, firma) return True except (ValueError, TypeError): return False
def verify(pk, msg, sgn): if not isinstance(pk, ECC.EccKey): pk = ECC.import_key(pk) verifier = DSS.new(pk, 'fips-186-3') h = SHA256.new(msg) try: verifier.verify(h, sgn) return True except ValueError as e: print("VerifyFailed: {}".format(e)) return False
def test_verify(self, tv): self._id = "Wycheproof DSA Test #" + str(tv.id) hashed_msg = tv.hash_module.new(tv.msg) signer = DSS.new(tv.key, 'fips-186-3', encoding='der') try: signature = signer.verify(hashed_msg, tv.sig) except ValueError as e: if tv.warning: return assert not tv.valid else: assert tv.valid self.warn(tv)
def create_genesis_transaction(private_key, public_key): # TODO: I don't think the genesis transaction needs inputs. It's the genesis, where is it getting its money from? """ Create the genesis transaction. :param private_key: :param public_key: :return: """ hashed_address = SHA256.new(public_key.encode('utf-8')).hexdigest() transaction = { "input_count": 1, "inputs": [ { "transaction_id": '', "output_index": -1, "unlock": { "public_key": public_key, "signature": '', } } ], "output_count": 1, "outputs": [ { "address": hashed_address, "amount": 7000 } ] } # fill the unlock signature transaction_message = SHA256.new(( # compose transaction message str(transaction['inputs'][0]['transaction_id']) + # input id str(transaction['inputs'][0]['output_index']) + # output index str(hashed_address) + # hashed public key as address str(transaction['outputs']) # new outputs ).encode()) signer = DSS.new(private_key, 'fips-186-3') signature = signer.sign(transaction_message) # sign the message encoded = base64.b64encode(signature).decode() transaction['inputs'][0]['unlock']['signature'] = encoded transaction_id = SHA256.new( str(transaction).encode('utf-8')).hexdigest() transaction['transaction_id'] = transaction_id return Transaction(payload=transaction)
def verify(self): # TODO: Maybe rename this function to authenticate """ Verify an incoming transaction. 1) SHA256 hash the unspent transaction object's address and SHA256 hash this transaction's signature script key and see if they match. If they do, continue. Otherwise return false. 2) Compose the transaction's message consisting of: - input transaction ID - input output index - unspent transaction object's public key script (hashed pubkey) - this transaction's public key script (s)? - this transaction's output amount (s)? and check to see if this transaction's signature can be verified by the now authorized signature script key. :return: True if the transaction is valid, false otherwise """ authentic = True for tnx_input in self.inputs: # for each referenced input utxo = find_unspent_output(tnx_input['transaction_id'], tnx_input['output_index'], tnx_input['block_hash']) sig_key = SHA256.new( # get this transaction's unlock public key tnx_input['unlock']['public_key'].encode() ).hexdigest() if sig_key == utxo['address']: # if this node is the recipient of # the previous utxo transaction_message = SHA256.new(( # transaction message str(tnx_input['transaction_id']) + # input id str(tnx_input['output_index']) + # output index str(utxo['address']) + # hashed public key as address str(self.outputs) ).encode('utf-8')) ecc_key = import_public_key(tnx_input['unlock']['public_key']) signature = tnx_input['unlock']['signature'] decoded = base64.b64decode(signature.encode()) verifier = DSS.new(ecc_key, 'fips-186-3') try: verifier.verify(transaction_message, decoded) except ValueError: authentic = False break return authentic
def test_asn1_encoding(self): """Verify ASN.1 encoding""" self.description = "ASN.1 encoding test" hash_obj = SHA1.new() signer = DSS.new(self.key_priv, 'fips-186-3', 'der') signature = signer.sign(hash_obj) # Verify that output looks like a SEQUENCE self.assertEqual(bord(signature[0]), 48) signer.verify(hash_obj, signature) # Verify that ASN.1 parsing fails as expected signature = bchr(7) + signature[1:] self.assertRaises(ValueError, signer.verify, hash_obj, signature)
def test_verify(self, tv): self._id = "Wycheproof ECDSA Test #%d (%s)" % (tv.id, tv.comment) hashed_msg = tv.hash_module.new(tv.msg) signer = DSS.new(tv.key, 'fips-186-3', encoding='der') try: signature = signer.verify(hashed_msg, tv.sig) except ValueError as e: if tv.warning: return if tv.comment == "k*G has a large x-coordinate": return assert not tv.valid else: assert tv.valid self.warn(tv)
def test1(self): q = 0x4000000000000000000020108A2E0CC0D99F8A5EF x = 0x09A4D6792295A7F730FC3F2B49CBC0F62E862272F p = 2 * q + 1 y = pow(2, x, p) key = DSA.construct([pow(y, 2, p), 2, p, q, x], False) signer = DSS.new(key, 'deterministic-rfc6979') # Test _int2octets self.assertEqual(hexlify(signer._int2octets(x)), b'009a4d6792295a7f730fc3f2b49cbc0f62e862272f') # Test _bits2octets h1 = SHA256.new(b"sample").digest() self.assertEqual(hexlify(signer._bits2octets(h1)), b'01795edf0d54db760f156d0dac04c0322b3a204224')
def unlock_inputs(self, private_key, public_key): """ Unlock previous unspent transaction outputs for a new transaction. Compose a transaction message consisting of: - input transaction ID - input output index - unspent transaction object's public key script (hashed pubkey) - this transaction's public key script (s)? - this transaction's output amount (s)? and sign it with this node's private key. Place a dict consisting of {key: public_key, sig: signature} in the corresponding input at "unlock" where `public_key` is this node's full public key and `signature` is the signed transaction message. """ if self.unused_amount != 0: # use up all input amounts (change) hash_address = SHA256.new(public_key.encode('utf-8')).hexdigest() self.outputs.append({ "address": hash_address, "amount": self.unused_amount }) self.output_count += 1 self.unused_amount = 0 for tnx_input in self.inputs: # for each input utxo = find_unspent_output(tnx_input['transaction_id'], tnx_input['output_index'], tnx_input['block_hash']) if utxo: transaction_message = SHA256.new(( # compose message str(tnx_input['transaction_id']) + str(tnx_input['output_index']) + str(utxo['address']) + # hashed public key address str(self.outputs) ).encode('utf-8')) signer = DSS.new(private_key, 'fips-186-3') signature = signer.sign(transaction_message) encoded = base64.b64encode(signature).decode() unlock = { # create unlocking portion of the transaction "public_key": public_key, "signature": encoded } tnx_input['unlock'] = unlock # assign to input. else: # TODO: raise error print("Invalid input found for {}".format(tnx_input))
"""This module helps user sign a file using DSS standard.""" from Crypto.Signature import DSS from Crypto.Hash import SHA256 from Crypto.PublicKey import DSA message = 'To be signed' key = DSA.importKey(open('dsa_key.bin').read()) h = SHA256.new(message) signer = DSS.new(key, 'fips-186-3') signature = signer.sign(h) print signature f = open("signature.bin", "wb") f.write(signature)
"""This module verifies a signature signed using DSS standard.""" from Crypto.Signature import DSS from Crypto.Hash import SHA256 from Crypto.PublicKey import DSA message = 'To be signed' key = DSA.importKey(open('pubkey.bin').read()) h = SHA256.new(message) verifier = DSS.new(key, 'fips-186-3') f = open("signature.bin", "rb") signature = f.read() try: verifier.verify(h, signature) print "The signature is authentic." except (ValueError, TypeError): print "The signature is not authentic."
if isinstance(tv, str): res = re.match("\[mod = L=([0-9]+), N=([0-9]+), ([a-zA-Z0-9-]+)\]", tv) hash_name = res.group(3).replace("-", "") hash_module = load_hash_by_name(hash_name) continue if hasattr(tv, "p"): modulus = tv.p generator = tv.g suborder = tv.q continue hash_obj = hash_module.new(tv.msg) key = DSA.construct([bytes_to_long(x) for x in (tv.y, generator, modulus, suborder)], False) verifier = DSS.new(key, 'fips-186-3') def positive_test(self, verifier=verifier, hash_obj=hash_obj, signature=tv.r+tv.s): verifier.verify(hash_obj, signature) def negative_test(self, verifier=verifier, hash_obj=hash_obj, signature=tv.r+tv.s): self.assertRaises(ValueError, verifier.verify, hash_obj, signature) if tv.result == 'p': setattr(FIPS_DSA_Tests, "test_verify_positive_%d" % idx, positive_test) else: setattr(FIPS_DSA_Tests, "test_verify_negative_%d" % idx, negative_test) test_vectors_sign = load_tests(("Crypto", "SelfTest", "Signature", "test_vectors", "DSA"), "FIPS_186_3_SigGen.txt",
def test_data_rfc6979(self): signer = DSS.new(self.key_priv, 'deterministic-rfc6979') for message, k, r, s, module in self.signatures: hash_obj = module.new(message) result = signer.sign(hash_obj) self.assertEqual(r + s, result)