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_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_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_negative_unapproved_hashes(self): """Verify that unapproved hashes are rejected""" from Cryptodome.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 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 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 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_asn1_encoding(self): """Verify ASN.1 encoding""" self.description = "ASN.1 encoding test" hash_obj = SHA256.new() signer = DSS.new(self.key_priv, 'fips-186-3', 'der') signature = signer.sign(hash_obj) # Verify that output looks like a DER 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 sign(key, msg): """ Firma un mensaje digitalmente con una clave privada. :param key: Una clave privada. :param msg: Un mensaje a firmar. :return: La firma digital del mensaje. :raise ValueError: Si la clave no tiene componente privada. """ if not key.has_private(): raise ValueError("La firma digital no tiene componente privada") msg_hash = SHA256.new(msg) dss = DSS.new(key=key, mode=MODE) return dss.sign(msg_hash)
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 verify(key, signature, msg): """ Verifica la validez de la firma sobre un mensaje. :param key: Una clave del par público-privado que pueda verificar la firma. :param signature: La firma digital. :param msg: El mensaje firmado. :return: `True` si la firma es válida, `False` en cualquier otro caso. """ try: dss = DSS.new(key=key, mode=MODE) dss.verify(signature=signature, msg_hash=SHA256.new(msg)) return True except ValueError: return False
def test_verify(self): # Ecdsa signature is not unique, so we only test if we can verify it pri_key = ECC.generate(curve="P-256") key = pri_key.export_key(format="DER") pub_key = pri_key.public_key() signer = Sha256WithEcdsaSigner("/K/KEY/x", key) pkt = make_data("/test", MetaInfo(), b"test content", signer=signer) _, _, _, sig_ptrs = parse_data(pkt) # Test its format is ASN.1 der format DerSequence().decode(bytes(sig_ptrs.signature_value_buf)) verifier = DSS.new(pub_key, 'fips-186-3', 'der') h = SHA256.new() for content in sig_ptrs.signature_covered_part: h.update(content) # verify() throws ValueError if it fails, the return value is undefined # So do not assert its value verifier.verify(h, bytes(sig_ptrs.signature_value_buf))
def test1(self): q = 0x4000000000000000000020108A2E0CC0D99F8A5EFL x = 0x09A4D6792295A7F730FC3F2B49CBC0F62E862272FL p = 2 * q + 1 y = pow(2, x, p) key = DSA.construct([pow(y, 2, p), 2L, p, q, x], False) signer = DSS.new(key, 'deterministic-rfc6979') # Test _int2octets self.assertEqual(hexlify(signer._int2octets(x)), b("009a4d6792295a7f730fc3f2b49cbc0f" "62e862272f")) # Test _bits2octets h1 = SHA256.new(b("sample")).digest() self.assertEqual(hexlify(signer._bits2octets(h1)), b("01795edf0d54db760f156d0dac04c032" "2b3a204224"))
def test_verify(self, tv): self._id = "Wycheproof ECDSA Test #%d (%s, %s)" % (tv.id, tv.comment, tv.filename) # Skip tests with unsupported curves if tv.key is None: return hashed_msg = tv.hash_module.new(tv.msg) signer = DSS.new(tv.key, 'fips-186-3', encoding=tv.encoding) 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 sign_image(image, key): """ Sign an image with the given private key """ stm32 = unpack_header(image) if stm32['magic'] != b'STM2': LOG.error('Not an STM32 header (signature FAIL)') return -1 stm32['ecdsa_pubkey'] = get_raw_pubkey(key) stm32['ecdsa_algo'] = key_algorithm(key) stm32['option_flags'] = 0 repack_header(image, stm32) sha = SHA256.new(image[0x48:]) signatory = DSS.new(key, 'fips-186-3') image[0x04:0x44] = signatory.sign(sha) verify_signature(image, key) LOG.debug('Signature: %s', stm32['signature'].hex()) return 0
def DummyClient(): """Starts a TCP client Connects to server Pings some data off of the server """ host = "127.0.0.1" #loopback adress port = 5555 socket1 = socket.socket() socket1.settimeout(1) socket1.connect((host, port)) key = ECC.generate(curve='P-256') publicKey = key.public_key().export_key(format='DER', compress=True).hex() print("publicKey :" + str(key.public_key().export_key(format='DER', compress=True))) protocallVersion = "0000" version = 'v0.0' clientName = "DummyClient" message = publicKey + ":" + protocallVersion + ":" + "bisclient" + ":" + clientName + ":" + version + ":" message = message.ljust(192, ' ') h1 = SHA256.new(message.ljust(256, " ").encode('utf-8')) signer = DSS.new(key, 'fips-186-3') signature = signer.sign(h1) handshake = message.encode('utf-8') + signature print("Sending data: " + str(handshake.hex())) socket1.send(handshake) data = socket1.recv(256) print("\tRecived data: " + str(data.hex())) #all communication should be encrypted beyond this point data = socket1.recv(4096).decode('utf-8') print("\tRecived data: " + str(data)) socket1.close()
async def verify_device_sign_on_ecdsa_signature( self, name: FormalName, sig: SignaturePtrs) -> bool: sig_info = sig.signature_info covered_part = sig.signature_covered_part sig_value = sig.signature_value_buf if not sig_info or sig_info.signature_type != SignatureType.SHA256_WITH_ECDSA: return False if not covered_part or not sig_value: return False device_identifier = Name.to_str([sig_info.key_locator.name[0]])[1:] logging.debug('Extract device id from key locator: %s', device_identifier) pk = None for ss in self.shared_secret_list.shared_secrets: if bytes(ss.device_identifier) == device_identifier.encode(): pub_key_bytes = bytes.fromhex(bytes(ss.public_key).decode()) pk = ECC.construct(curve='p256', point_x=int.from_bytes(pub_key_bytes[:32], byteorder='big'), point_y=int.from_bytes(pub_key_bytes[32:], byteorder='big')) # pk = ECC.import_key(bytes(ss.public_key)) break if not pk: logging.error( "[SIGN ON]: no pre-shared public key about the device") return False verifier = DSS.new(pk, 'fips-186-3', 'der') sha256_hash = SHA256.new() for blk in covered_part: sha256_hash.update(blk) logging.debug(bytes(sig_value)) logging.debug(len(bytes(sig_value))) try: verifier.verify(sha256_hash, bytes(sig_value)) except ValueError: return False return True
async def wrapper(name:FormalName, sig:SignaturePtrs) -> bool: nonlocal key_bits sig_info = sig.signature_info covered_part = sig.signature_covered_part sig_value = sig.signature_value_buf if sig_info and sig_info.signature_type == SignatureType.SHA256_WITH_ECDSA: if sig_info.key_locator.name != key_name: return False pub_key = ECC.import_key(key_bits) verifier = DSS.new(pub_key, 'fips-186-3', 'der') sha256_algo = SHA256.new() if not covered_part or not sig_value: ret = False else: for blk in covered_part: sha256_algo.update(blk) try: verifier.verify(sha256_algo, bytes(sig_value)) return True except ValueError: return False SVSyncLogger.debug(f'Digest check {Name.to_str(name)} -> {ret}') return ret return False
def verify_signature(image, key): """ Verify the signature of the binary """ hdr = unpack_header(image) signature = hdr['signature'] image_pubkey = hdr['ecdsa_pubkey'] raw_pubkey = get_raw_pubkey(key) if raw_pubkey != image_pubkey: print('Image is not signed with the provided key') return 1 sha = SHA256.new(image[0x48:]) verifier = DSS.new(key, 'fips-186-3') try: verifier.verify(sha, signature) LOG.info('Signature checks out') except ValueError: LOG.error('The signature is fake news') LOG.error('Found: %s', signature.hex()) return 2 return 0
def on_challenge_interest(name: FormalName, param: InterestParam, _app_param: Optional[BinaryStr]): global client_self_signed, testbed_signed, signer, token logging.info("Challenge interest") # extract client public key bits client_pub_key = bytes(testbed_signed.content) # verify verifier = DSS.new(ECC.import_key(client_pub_key), 'fips-186-3', 'der') sha256_hash = SHA256.new() sha256_hash.update(token) try: verifier.verify(sha256_hash, bytes(_app_param)) except ValueError: # proof-of-possesion failed logging.info("Proof-of-possesion failed") content = "proof-of-possesion failed".encode() app.put_data(name, content=content, freshness_period=10000, signer=signer) return # we can derive a new cert for client logging.debug("Proof-of-possesion succeed") client_key_name = client_self_signed.name[:-2] issuer_id = "icear-server" start_time = date.fromtimestamp(time.time()) expire_sec = timedelta(days=30).total_seconds() cert_name, wire = derive_cert(client_key_name, issuer_id, client_pub_key, signer, start_time, expire_sec) logging.info("Newly issused certificate: %s", Name.to_str(cert_name)) app.put_data(name, content=wire, freshness_period=10000, signer=signer)
ECC = object() _key_kind_pycrypto_map = {KeyKind.RSA: RSA, KeyKind.DSA: DSA, KeyKind.ECC: ECC} _key_oid_kind_map = { "1.2.840.113549.1.1.1": KeyKind.RSA, "1.2.840.10040.4.1": KeyKind.DSA, "1.2.840.10045.2.1": KeyKind.ECC, # id-ecPublicKey "1.3.132.1.12": KeyKind.ECC, # id-ecDH "1.3.132.1.13": KeyKind.ECC, # id-ecMQV } _key_signature_scheme_map = { KeyKind.RSA: pkcs1_15.new, KeyKind.DSA: lambda key: DSS.new(key, "fips-186-3", encoding="der"), KeyKind.ECC: lambda key: DSS.new(key, "fips-186-3", encoding="der"), } class PublicKeyCodecBase: _CodecDict = asn1tools.parse_string( """ -- Simplified public key definition based on IETF/RFC5912 -- Support RSA, DSA and ECC (**named curve only**) public keys SimplifiedPublicKey DEFINITIONS IMPLICIT TAGS ::= BEGIN PublicKey ::= SEQUENCE { algorithm SEQUENCE { algorithmIdentifier OBJECT IDENTIFIER, algorithmParameters CHOICE {
logging.basicConfig(format='%(message)s', level=logging.INFO, stream=sys.stderr) log = logging.getLogger() BASE64_STANDARD = b'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' BASE64_CUSTOM = b'HJIA/CB+FGKLNOP3RSlUVWXYZfbcdeaghi5kmn0pqrstuvwx89o12467MEDyzQjT' ECC_KEY = '''-----BEGIN PUBLIC KEY----- MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE8yCG2yBN8HM3tfsYsMCvgLvz+/FKwDvG AB8j7xxMBlSjj6YZfEFX6wu8f0GhWHlwDcOhOBxe4nrRKfu2VUHVjsfHPh7ztGdj 01D1W1/RwFa4OIfbtUTX4Th5PmMrAy7I -----END PUBLIC KEY----- ''' verifier = DSS.new(ECC.import_key(ECC_KEY), 'fips-186-3') def derive_key(rounds, data): h = SHA256.new() for _ in range(rounds): h.update(data) data = h.digest() return data def decrypt_data(data): if data is None: return None key = derive_key(128, data[:0x20])[:0x20]
def do_crypto_shit(self, key): signer = DSS.new(key, 'fips-186-3') self.key = key.public_key self.chunk_hash = SHA256.new(self.to_json().encode()) self.signature = signer.sign(self.chunk_hash) return
from Cryptodome.Hash import SHA256 from Cryptodome.PublicKey import DSA from base64 import b64encode secret = "Change this to something unguessable!" # Read secret key f_key = open('./secret_key.pem').read() key = DSA.import_key(f_key, passphrase=secret) # Create message hash message = b"2017-12-19T10:59:50.797961" hash_obj = SHA256.new(message) print('hash: ', b64encode(hash_obj.digest())) # Sign the message hash signer = DSS.new(key, 'fips-186-3') signature = signer.sign(hash_obj) print('signature: ', b64encode(signature)) # Load the public key f = open("public_key.pem", "r") pub_key = DSA.import_key(f.read()) # Create the hash again for verification check_hash_obj = SHA256.new(message) print('check_hash: ', b64encode(check_hash_obj.digest())) # Verify the authenticity of the message verifier = DSS.new(key, 'fips-186-3') try: verifier.verify(check_hash_obj, signature)
if isinstance(tv, basestring): 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(("Cryptodome", "SelfTest", "Signature", "test_vectors", "DSA"), "FIPS_186_3_SigGen.txt",
from Cryptodome.PublicKey import ECC key = None if not os.path.exists('myprivatekey.pem'): print("creating new ECC private key") key = ECC.generate(curve='P-256') f = open('mypublickey.pem', 'wt') f.write(key.public_key().export_key(format='PEM')) f.close() f = open('myprivatekey.pem', 'wt') f.write(key.export_key(format='PEM')) f.close() else: print("reading existing key") f = open('myprivatekey.pem', 'rt') key = ECC.import_key(f.read()) f.close() h = SHA256.new("message".encode()) signer = DSS.new(key, 'fips-186-3') signature = signer.sign(h) h = SHA256.new("message".encode()) verifier = DSS.new(key.public_key(), 'fips-186-3') try: verifier.verify(h, signature) print("The message is authentic.") except ValueError: print("The message is not authentic.")
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)
options = json.loads(file.read()) file.close() #load Globals HostIP = options["hostIP"] HostPort = options["hostPort"] PrivateKey = ECC.import_key(bytes(bytearray.fromhex(options["privateKeyHex"]))) Nodes = {} del(options) PublicKeyHex = ((PrivateKey.public_key().export_key(format='DER', compress=True)).hex()).ljust(128, "0") #TODO this is shortcut, have actual machinery to swap out encryption implimentations message = PublicKeyHex + ":" + str(ProtocalVersion) + ":" + "bootstrap" + ":" + str(ProgramName) + ":" + str(ProgramVersion) + ":" message = message.ljust(192, ' ') h1 = SHA256.new(message.encode(encoding='utf-8')) signer = DSS.new(PrivateKey, 'fips-186-3') signature = signer.sign(h1) Handshake = message.encode(encoding='utf-8') + signature print(Handshake) print(len(Handshake)) print(Handshake.hex()) print(PublicKeyHex) #start listening socket1 = socket.socket() socket1.bind((HostIP, HostPort)) socket1.settimeout(1) socket1.listen(512)
def calculate_signature(data, key_data=_PRIVATE_KEY): key = ECC.import_key(key_data) signer = DSS.new(key, 'fips-186-3') return signer.sign(SHA256.new(data))
from Cryptodome.Hash import SHA256 private_key = DSA.generate(2048) # $ PublicKeyGeneration keySize=2048 public_key = private_key.publickey() # ------------------------------------------------------------------------------ # sign/verify # ------------------------------------------------------------------------------ print("sign/verify") message = b"message" signer = DSS.new(private_key, mode='fips-186-3') hasher = SHA256.new(message) # $ CryptographicOperation CryptographicOperationAlgorithm=SHA256 CryptographicOperationInput=message signature = signer.sign(hasher) # $ CryptographicOperation CryptographicOperationInput=hasher # MISSING: CryptographicOperationAlgorithm=DSA print("signature={}".format(signature)) print() verifier = DSS.new(public_key, mode='fips-186-3') hasher = SHA256.new(message) # $ CryptographicOperation CryptographicOperationAlgorithm=SHA256 CryptographicOperationInput=message verifier.verify(hasher, signature) # $ CryptographicOperation CryptographicOperationInput=hasher CryptographicOperationInput=signature # MISSING: CryptographicOperationAlgorithm=DSA print("Signature verified (as expected)") try:
async def main(): global local_anchor import_safebag("sec/client.safebag", "1234") # parse again to read prv key into memory request = CertRequest() with open("sec/client.safebag", "r") as safebag: wire = safebag.read() wire = base64.b64decode(wire) wire = parse_and_check_tl(wire, SecurityV2TypeNumber.SAFE_BAG) bag = SafeBag.parse(wire) # attach the testbed-signed certificate request.testbed_signed = bag.certificate_v2 # parse the key bag to obtain private key testbed_signed = CertificateV2Value.parse(bag.certificate_v2) key_bag = bytes(bag.encrypted_key_bag) privateKey = serialization.load_der_private_key(key_bag, password=b'1234', backend=default_backend()) client_prv_key = privateKey.private_bytes(Encoding.DER, PrivateFormat.PKCS8, NoEncryption()) # parse trust anchor and self-assigns a name, then create self-signed certificate with open("sec/client.anchor", "r") as anchor: wire = anchor.read() wire = base64.b64decode(wire) local_anchor = parse_certificate(wire) # self-assign a name and create corresponding key pair client_name = local_anchor.name[:-4] + [testbed_signed.name[-5]] client_identity = app.keychain.touch_identity(client_name) # attach newly generated self-assigned certificate cert = client_identity.default_key().default_cert().data cert = parse_certificate(cert) request.self_signed = cert.encode() try: # express the first interest to fetch a token/secret code timestamp = ndn.utils.timestamp() name = Name.from_str('/edge/_ca/new-cert') + [Component.from_timestamp(timestamp)] logging.info(f'Sending Interest {Name.to_str(name)}, {InterestParam(must_be_fresh=True, lifetime=6000)}') data_name, meta_info, content = await app.express_interest( name, app_param=request.encode(), must_be_fresh=True, can_be_prefix=False, lifetime=6000, identity=client_identity, validator=verify_ecdsa_signature) # sign it use the private key, to prove the certificate possesion h = SHA256.new() h.update(bytes(content)) pk = ECC.import_key(client_prv_key) signature = DSS.new(pk, 'fips-186-3', 'der').sign(h) logging.info(f'Getting Data {Name.to_str(name)}, begin signing the token {bytes(content)}') # express the second interest to fetch the issued certificate name = Name.from_str('/edge/_ca/challenge') + [Component.from_timestamp(timestamp)] logging.info(f'Sending Interest {Name.to_str(name)}, {InterestParam(must_be_fresh=True, lifetime=6000)}') data_name, meta_info, content = await app.express_interest( name, app_param=signature, must_be_fresh=True, can_be_prefix=False, lifetime=6000, identity=client_identity, validator=verify_ecdsa_signature) # parse the issued certificate and install issued_cert = parse_certificate(content) logging.info("Issued certificate: %s", Name.to_str(issued_cert.name)) app.keychain.import_cert(Name.to_bytes(issued_cert.name[:-2]), Name.to_bytes(issued_cert.name), bytes(content)) except InterestNack as e: print(f'Nacked with reason={e.reason}') except InterestTimeout: print(f'Timeout') except InterestCanceled: print(f'Canceled') except ValidationFailure: print(f'Data failed to validate') app.shutdown()
from Cryptodome.Signature import DSS from Cryptodome.Hash import SHA256 from Cryptodome.PublicKey import DSA from base64 import b64decode import json # Load the public key f = open('public_key.pem', 'r') pub_key = DSA.import_key(f.read()) # Read JSON input json_string = '{"output": "Signed timestamp", "timestamp": "2017-12-19T14:07:39.149933", "signature": "qJVvJcBTUxpv63chyx3dCt43YueMe4fF8/G/qsRHbriSflkHIfUIgSM6rCy387Hx811zxHXSs34="}' parsed_json = json.loads(json_string) timestamp = parsed_json['timestamp'] print('timestamp: ', timestamp) signature = parsed_json['signature'] print('signature: ', signature) # Create the hash for verification hash_obj = SHA256.new(timestamp.encode('utf-8')) print('hash: ', hash_obj.digest()) # Verify the authenticity of the message verifier = DSS.new(pub_key, 'fips-186-3') try: verifier.verify(hash_obj, b64decode(signature)) print('The message is authentic.') except ValueError: print('Message failed authentication!')
def _ecdsa(private_key: EccKey, *args) -> FipsEcDsaSigScheme: return DSS.new(private_key, 'fips-186-3').sign(_sha256(*args))
print("PublicKey Compressed:\n" + str(publicKey1.hex())) print("Length: " + str(len(publicKey1))) publicKey2 = key.public_key().export_key(format='DER', compress=False) print("PublicKey:\n" + str(publicKey2.hex())) print("Length: " + str(len(publicKey2))) #sign a message # http://pycryptodome.readthedocs.io/en/latest/src/signature/dsa.html from Cryptodome.Hash import SHA256 #can use SHA512 (and others) as well from Cryptodome.Signature import DSS message = "This is a test".ljust(256,"_") h1 = SHA256.new(message.encode()) print("Message hash generator: " + str(h1)) signer = DSS.new(key, 'fips-186-3') signature = signer.sign(h1) print("Signiture:\n" + str(signature.hex())) print("Length: " + str(len(signature))) ''' test = bytearray(len(publicKey1)) for i in range(0,len(publicKey1)): if i != 56: test[i] = publicKey1[i] else: test[i] = 0 test = bytes(test) print(test.hex()) '''
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_KAT, "test_verify_positive_%d" % idx,
listY.append(fy.rstrip("\n")) archivo.close() P = int(listP[0], 16) Q = int(listQ[0], 16) G = int(listG[0], 16) for i in range(0, 4): for i in range(0, len(listMsg)): Msg = bytearray.fromhex(listMsg[i]) X = int(listX[i], 16) Y = int(listY[i], 16) #K =int("85976c5610a74959531040a5512b347eac587e48",16) key = DSA.construct((Y, G, P, Q, X)) timeI = time() firma = DSS.new(key, "fips-186-3") h = SHA256.new(Msg) sign_fir = firma.sign(h) timeF = time() timeGenDSA.append(timeF - timeI) #print("Generar firma:") #print(sign_fir.hex()) #VERIFICAR FIRMA listP = [] #Lista del parametro P listQ = [] #Lista del parametro Q listG = [] #Lista del parametro G listMsg = [] #Lista de los mensajes listX = [] #Lista del parametro X listY = [] #Lista del parametro Y listR = [] #Lista de firmas R
def verify_signature(data, signature, key_data=_PUBLIC_KEY): key = ECC.import_key(key_data) verifier = DSS.new(key, 'fips-186-3') verifier.verify(SHA256.new(data), signature)
def sign(self, message): """create signature for a message""" h = SHA256.new(message) signer = DSS.new(self.key, 'fips-186-3') signature = signer.sign(h) return signature