def verify(self, sig, data): h = SHA256.new(data) try: pss.new(self.key).verify(h, sig) return True except: return False
def verify_signature(key, data, s): try: pss.new(import_key(key)).verify(sha256(data), s) except (ValueError, TypeError): print('The signature is not authentic') sys.exit(1) print('The signature is authentic')
def RSA_PSS(data, n, e, d): privateKeyRSA = RSA.construct((n, e, d)) publicKeyRSA = privateKeyRSA.publickey() times = [] hashValue = SHA256.new(data) signFunction = pss.new(privateKeyRSA) start = time.clock() signature = signFunction.sign(hashValue) end = time.clock() print(signature.hex()) times.append(end - start) verifier = pss.new(publicKeyRSA) try: start = time.clock() verifier.verify(hashValue, signature) end = time.clock() print("The signature is authentic.") except (ValueError, TypeError): print("The signature is not authentic.") times.append(end - start) return times
def sign(self, path_input: str, path_private_key: str, path_public_key: str, passphrase: str) -> None: """ Sign and verify signature of a file :param path_input: path of source file :param path_private_key: :param path_public_key: :param passphrase: """ # Init content, private and public keys content = load_file(path_input) private_key = RSA.import_key(load_file(path_private_key), passphrase) public_key = RSA.import_key(load_file(path_public_key), passphrase) # Hash and sign content hash_content = SHA256.new(data=content.encode()) signature = pss.new(private_key).sign(hash_content) # Verify signature of the content verify = pss.new(public_key) try: verify.verify(hash_content, signature) print(Format.LIST_INFO + Colors.INFO + "The signature is authentic!\n" + Colors.ENDC) except (ValueError, TypeError): print(Format.LIST_ERROR + Colors.FAIL + "The signature is not authentic!\n" + Colors.ENDC)
def autenticar_firma(self, mensaje, firma, publickey): #Hacemos hash del mensaje hash_msj = SHA256.new(data=mensaje) #Verificamos la firma con el hash y la clave publica try: pss.new(publickey).verify(hash_msj,firma) return True except: return False
def doRSA(vectors, RSA_mode): counter = 0 #This variable stores the numbers of vectors read addition1 = 0 #This variable stores execution times for encrypt/sign addition2 = 0 #This variable stores execution times for decrypt/verify key = RSA.generate(1024) #a random key is created (1024 bits) cipher_PKCS1 = PKCS1_OAEP.new(key) #a RSA-OAEP cipher object is created for vector in vectors: counter += 1 data = bytes.fromhex( vector) #vector is converted from hex to a binary object if RSA_mode == "OAEP": # Encrypt start = timer() #begin time measure data_in = cipher_PKCS1.encrypt(data) #message encryption end = timer() #end time measure #print(end-start) #total execution time addition1 += end - start # Decrypt start = timer() #begin time measure data_out = cipher_PKCS1.decrypt(data_in) #message decryption end = timer() #end time measure #print(end-start) #total execution time addition2 += end - start # Print result #for i in range(len(data_in)): # print('{:0>2X}'.format(data_in[i]), end='') #print("") elif RSA_mode == "PSS": # Signature start = timer() #begin time measure h = SHA384.new(data) data_out = pss.new(key).sign(h) #hash is signed with private key end = timer() #end time measure #print(end-start) #total execution time addition1 += end - start # Verification start = timer() #begin time measure h = SHA384.new(data) verifier = pss.new(key) #verifier uses the public key try: verifier.verify(h, data_out) #data is verified end = timer() #end time measure #print(end-start) #total execution time addition2 += end - start #print("The signature is authentic.") except (ValueError, TypeError): pass #print("The signature is not authentic.") #for i in range(len(data_out)): # print('{:0>2X}'.format(data_out[i]), end='') #print("") return addition1 / counter, addition2 / counter
def test_mismatch_keypair(self): keypair0 = utils.generate_key_pair() keypair1 = utils.generate_key_pair() key = RSA.importKey(keypair0["private"]) pubkey = RSA.importKey(keypair1["public"]) message = "The quick brown fox jumps over the lazy dog." h = SHA256.new(message) sig = pss.new(key).sign(h) with self.assertRaises(ValueError): pss.new(pubkey).verify(h, sig)
def verify(filename, sign): with open(filename, "r") as file: data = file.read().replace('\n', '').encode('utf-8') public_key = get_public_key() signature = base64.b64decode(sign) msg_hash = SHA256.new(data) try: pss.new(public_key).verify(msg_hash, signature) return True except Exception as ex: logger.debug(ex) return False
def test_key_pair(self): keypair = utils.generate_key_pair() key = RSA.importKey(keypair["private"]) pubkey = RSA.importKey(keypair["public"]) message = "The quick brown fox jumps over the lazy dog." h = SHA256.new(message) sig = pss.new(key).sign(h) try: pss.new(pubkey).verify(h, sig) except ValueError: self.fail()
def sign(self, message, privKeyPath, password): if type(message) is str: message = message.encode('utf-8') key = RSA.importKey(BasicFunctions.binaryReader(privKeyPath), password) Hash = SHA3_512.new(message) signature = pss.new(key).sign(Hash) return signature
def do_sign_ds4id(p, args): ca_pss = None if args.jedi_ca_privkey is not None: ca, _ = _load_key_and_check(args.jedi_ca_privkey, JEDI_CA_PUBKEY_FINGERPRINT) ca_pss = pss.new(ca) if not ca_pss.can_sign(): raise TypeError('Jedi CA private key not present in the key file.') with disconnectable(_do_connect_and_select(p, args)) as conn: if ca_pss is not None: print('Exporting DS4ID from card...') ds4id_signed = _do_export_ds4id(conn) sha_id = SHA256.new(bytes(ds4id_signed.identity)) sig = ca_pss.sign(sha_id) else: assert args.sig_binary is not None with open(args.sig_binary, 'rb') as f: sig = f.read() if len(sig) != 0x100: raise TypeError('Wrong signature file size.') print('Importing new signature...') resp, sw1, sw2 = conn.transmit( APDU(ISCCLA.config, ISCConfigINS.import_, ISCImportType.sig_id, 0x00, payload=sig).to_list()) _check_error(resp, sw1, sw2)
def enc_accept(src, ssid): # compute message length... # header: 5 bytes # type: 1 byte [0:1] # invite: 1, accept: 2 # version: 2 bytes [1:3] # length: 2 bytes [3:5] # user's id: 1 bytes [5:6] # hash invite: 64 bytes # signature: 256 bytes RSA signature scheme msg_length = 5 + 1 + 64 + 256 # create header header_type = b'\x02' # message type 1 header_version = b'\x03\x06' # protocol version 3.6 header_length = msg_length.to_bytes(2, byteorder='big') # message length (encoded on 2 bytes) header = header_type + header_version + header_length # create admin's id and number of participants user_id = src.encode() ssid = ssid.encode() content = header + user_id + ssid keypair = genkey.load_keypair(NETPATH + '/' + src + '/' +'privkey.pem') signer = pss.new(keypair) hashfn = SHA256.new() hashfn.update(content) signature = signer.sign(hashfn) content += signature return content
def _sign_digest(self, digest): """Signs a message digest with a private key specified in the signing_info. :param digest: A hashing object that contains the cryptographic digest of the HTTP request. :return: A base-64 string representing the cryptographic signature of the input digest. """ sig_alg = self.signing_algorithm if isinstance(self.private_key, RSA.RsaKey): if sig_alg is None or sig_alg == ALGORITHM_RSASSA_PSS: # RSASSA-PSS in Section 8.1 of RFC8017. signature = pss.new(self.private_key).sign(digest) elif sig_alg == ALGORITHM_RSASSA_PKCS1v15: # RSASSA-PKCS1-v1_5 in Section 8.2 of RFC8017. signature = PKCS1_v1_5.new(self.private_key).sign(digest) else: raise Exception( "Unsupported signature algorithm: {0}".format(sig_alg)) elif isinstance(self.private_key, ECC.EccKey): if sig_alg is None: sig_alg = ALGORITHM_ECDSA_MODE_FIPS_186_3 if sig_alg in ALGORITHM_ECDSA_KEY_SIGNING_ALGORITHMS: signature = DSS.new(self.private_key, sig_alg).sign(digest) else: raise Exception( "Unsupported signature algorithm: {0}".format(sig_alg)) else: raise Exception("Unsupported private key: {0}".format( type(self.private_key))) return b64encode(signature)
def RSA_PSS_verify(message, key, sign): try: h = SHA256.new(message) verifier = pss.new(key) verifier.verify(h, sign) except ValueError: print('The message is not authentic')
def verify(self, pubKey: KeyT, signature: bytes, msg_hash: Callable) -> NoReturn: """ Verificar un mensaje firmado. :param pubKey: La clave pública para la verificación del mensaje firmado. :type pubKey: str/bytes :param signature: El mensaje firmado. :type signature: bytes :param msg_hash: La instancia de un nuevo objeto '<Hash>.new(b'<datos>')'. Nota: Debe incluir el mensaje en 'new' para compararlo con la firma. :type msg_hash: Callable :Return: No retorna nada si no se generó un error. """ _publicKey = self.import_public_key(pubKey, False) _pss = pss.new(_publicKey) _pss.verify(msg_hash, signature)
def signature_check(filename, public_key): try: src_file = open(filename, "rb") except FileNotFoundError: print("No such file! Try again!") return data = src_file.read() src_hash = SHA256.new(data) try: public_file = open(public_key, "rb") except FileNotFoundError: print("No such file! Try again!") return key = RSA.import_key(public_file.read()) cipher = pss.new(key) try: try: signature = open("keys/" + "signature" + ".sign", "rb").read() except FileNotFoundError: print("No such file! Try again!") return cipher.verify(src_hash, signature) print("The signature is authentic.") except (ValueError, TypeError): print("The signature is not authentic.")
def send_ack_initial_connection(self, private_key): """ * Responds to the client connection """ rsa_private_key = RSA.importKey(private_key) rsa_key = PKCS1_OAEP.new(rsa_private_key) Nb = uuid.uuid4() encrypted_msg = self.socket.recv(512) msg = rsa_key.decrypt(encrypted_msg) name = msg[-5:] print(name) # if msg[-5:] != "Alice": # conn.close() Na = msg[:-5] print("Na recv", Na) print("Nb ", Nb.bytes) msg = "Bob".encode() + Na sha = SHA256.new(msg) # print("len sha ",len(sha.digest()) ) # print("len Nb ",len(Nb.encode())) # print("pad length ",len(pad(Nb.bytes,32))) msg = strxor(sha.digest(), pad(Nb.bytes, 32)) integrity = pss.new(rsa_private_key).sign(SHA256.new(msg)) length = 32 + 512 self.socket.send(self.int_to_bytes(length, 2)) self.socket.send(msg + integrity) # self.socket.send(integrity) session = strxor(Na, Nb.bytes) return session
def generate_fake_generations(): genesis_account = Account.objects.get(address=GENESIS_ADDRESS) num_transactions = random.randint(1, MAX_TX_PER_BLOCK) with open("genesisprivatekey.pem", "r") as f: key = RSA.import_key(f.read()) transactions = [] print("there are " + str(num_transactions) + "transactions generated in this block") for _ in range(num_transactions): amount = Decimal(str(random.randint(0, 10))) target_address = random.choice(account_addresses) target_account = Account.objects.get(address=target_address) genesis_transactions = Transaction.objects.filter( sender=genesis_account) nonce = len(genesis_transactions) + 1 transaction = Transaction.objects.create(sender=genesis_account, amount=amount, receiver=target_account, nonce=nonce) transaction.transaction_hash = transaction.hash_hex() transaction.signature = pss.new(key).sign( transaction.hash_transaction()) transaction.save() transactions.append(transaction) return transactions
def getContentKey(self, lic_request_data): license = license_protocol_pb2.License() requestMessage = license_protocol_pb2.SignedMessage() responseMessage = license_protocol_pb2.SignedMessage() resp = requests.post(self.license_url, lic_request_data, headers=self.header, proxies=self.proxies) requestMessage.ParseFromString(lic_request_data) responseMessage.ParseFromString(resp.content) pubkey = RSA.importKey(self.pub_key) verifier = pss.new(pubkey) h = SHA1.new(requestMessage.msg) verifier.verify(h, requestMessage.signature) session_key = responseMessage.session_key license.ParseFromString(responseMessage.msg) rsakey = RSA.importKey(self.private_key) cipher = PKCS1_OAEP.new(rsakey) sessionKey = cipher.decrypt(session_key) context_enc = '\x01' + 'ENCRYPTION' + '\x00' + requestMessage.msg + '\x00' * 3 + chr( 128) cobj = CMAC.new(sessionKey, ciphermod=AES) encryptKey = cobj.update(context_enc).digest() k = license.key[1] keyId = k.id.encode('hex') keyData = k.key[0:16] keyIv = k.iv[0:16] mode = AES.MODE_CBC cryptos = AES.new(encryptKey, mode, keyIv) dkey = cryptos.decrypt(keyData) print "KID:", keyId, "KEY:", dkey.encode('hex')
def verify_message_signature(*, message: bytes, signature_algo: str, signature: dict, key: Union[KNOWN_KEY_TYPES]): """Verify the authenticity of a signature. Raises if signature is invalid. :param message: the bytestring which was signed :param signature_algo: the name of the signing algorithm :param signature: structure describing the signature :param key: the cryptographic key used to verify the signature """ # TODO refactor this with new SIGNATURE_ALGOS_REGISTRY fields signature_algo = signature_algo.upper() if signature_algo == "RSA_PSS": verifier = pss.new(key) elif signature_algo in ["DSA_DSS", "ECC_DSS"]: verifier = DSS.new(key, "fips-186-3") else: raise ValueError("Unknown signature algorithm %s" % signature_algo) hash_payload = _compute_timestamped_hash( message=message, timestamp_utc=signature["timestamp_utc"]) try: verifier.verify(hash_payload, signature["digest"]) except ValueError as exc: raise SignatureVerificationError( "Failed %s signature verification (%s)" % (signature_algo, exc)) from exc
def firmarRSA_PSS(texto, key_private): h = SHA256.new( texto.encode("utf-8")) # Ya veremos los hash la semana que viene print(h.hexdigest()) signature = pss.new(key_private).sign(h) return signature
def verify(rsa_pk, h, signature): verif = pss.new(rsa_pk) try: verif.verify(h, signature) return True except (ValueError, TypeError): return False
def firmar(self, datos): """Firma el parámetro datos (de tipo binario) con la clave self.private_key, y devuelve el resultado. En caso de error, se devuelve None.""" if self.private_key is None: return None h = SHA256.new(datos) signature = pss.new(self.private_key).sign(h) return signature
def new(rsa_key, mgfunc=None, saltLen=None, randfunc=None): pkcs1 = pss.new(rsa_key, mask_func=mgfunc, salt_bytes=saltLen, rand_func=randfunc) pkcs1._verify = pkcs1.verify pkcs1.verify = types.MethodType(_pycrypto_verify, pkcs1) return pkcs1
def verify_signature(signature, hash_of_file, public_key): """Sign the hash of file with the key.""" verifier = pss.new(public_key) try: verifier.verify(hash_of_file, signature) print "The signature is authentic." except (ValueError, TypeError): print "The signature is not authentic."
def verify(m, s, public_key): h = SHA256.new(m) verifier = pss.new(RSA.importKey(public_key)) try: verifier.verify(h, s) print('Signature is valid') except (TypeError, ValueError): print('Invalid Signature')
def sign_transaction(self, private_key): """Sign the current transaction with the given private key.""" message = self.transaction_id.encode("ISO-8859-1") key = RSA.importKey(private_key.encode("ISO-8859-1")) h = SHA256.new(message) signer = pss.new(key) self.signature = signer.sign(h).decode('ISO-8859-1')
def firmar(self,datos): h = SHA256.new(datos.encode("utf-8")) print(h.hexdigest) try: signature = pss.new(self.key_private).sign(h) return signature except ValueError: return None
def verify(self,message): message = bytes.fromhex(message) #Convierte el mensaje a bytes. random_generator = Random.new().read #Genera una secuencia aleatoria. key = RSA.generate(1024,random_generator) #Se usa la secuencia para generar un par de llaves. h = SHA256.new(message) #Se obtiene la transformada hash del mensaje. signature = pss.new(key).sign(h) #Se crea un objeto que permite hacer la firma y validación. start_time = timer() #Se empieza a tomar el tiempo de ejecución. verifier = pss.new(key.publickey()) #Se crea el objeto capaz de validar la firma, para ello se usa la llave pública. try: verifier.verify(h,signature) #Función que hace la valdiación de la firma. self.executionTime = timer() - start_time #Fin de la toma de tiempo. print("La firma es correcta.") return 1 #La firma es auténtica. except(ValueError, TypeError): self.executionTime = timer() - start_time #fin de la toma de tiempo. print("La firma no es correcta.") return 0 #La firma no es auténtica.
def verify(self, msg: bytes, signature: bytes): # 这里的验证似乎不太对 但影响不大 # e.g. self.verify(requestMessage.msg, requestMessage.signature) _hash = SHA1.new(msg) public_key = RSA.importKey(self.public_key) verifier = pss.new(public_key) res = verifier.verify(_hash, signature) print(f"verify result is --> {res}")
def runTest(self): key = RSA.generate(1280) signer = pss.new(key) hash_names = ("MD2", "MD4", "MD5", "RIPEMD160", "SHA1", "SHA224", "SHA256", "SHA384", "SHA512", "SHA3_224", "SHA3_256", "SHA3_384", "SHA3_512") for name in hash_names: hashed = load_hash_by_name(name).new(b("Test")) signer.sign(hashed) from Crypto.Hash import BLAKE2b, BLAKE2s for hash_size in (20, 32, 48, 64): hashed_b = BLAKE2b.new(digest_bytes=hash_size, data=b("Test")) signer.sign(hashed_b) for hash_size in (16, 20, 28, 32): hashed_s = BLAKE2s.new(digest_bytes=hash_size, data=b("Test")) signer.sign(hashed_s)
def _test_sign(self, hashmod, message, private_key, salt, signature): prng = PRNG(salt) hashed = hashmod.new(message) signer = pss.new(private_key, salt_bytes=len(salt), rand_func=prng) signature2 = signer.sign(hashed) self.assertEqual(signature, signature2)
"""This module helps user sign a file using PKCS1 PSS standard.""" from Crypto.Signature import pss from Crypto.Hash import SHA256 from Crypto.PublicKey import RSA # from Crypto import Random message = 'To be signed' key = RSA.importKey(open('rsa_key.bin').read()) h = SHA256.new(message) signature = pss.new(key).sign(h) print signature f = open("signature.bin", "wb") f.write(signature)
def sign_file(key, hash_of_file): """Sign the hash of file with the key.""" signature = pss.new(key).sign(hash_of_file) return signature
"""This module verifies a signature signed using PKCS1 PSS standard.""" from Crypto.Signature import pss from Crypto.Hash import SHA256 from Crypto.PublicKey import RSA # from Crypto import Random message = 'To be signed' key = RSA.importKey(open('pubkey.bin').read()) h = SHA256.new(message) verifier = pss.new(key) 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."
for count, tv in enumerate(test_vectors_verify): if isinstance(tv, basestring): continue if hasattr(tv, "n"): modulus = tv.n continue if hasattr(tv, "p"): continue hash_module = load_hash_by_name(tv.shaalg.upper()) hash_obj = hash_module.new(tv.msg) public_key = RSA.construct([bytes_to_long(x) for x in modulus, tv.e]) if tv.saltval != b("\x00"): prng = PRNG(tv.saltval) verifier = pss.new(public_key, salt_bytes=len(tv.saltval), rand_func=prng) else: verifier = pss.new(public_key, salt_bytes=0) def positive_test(self, hash_obj=hash_obj, verifier=verifier, signature=tv.s): verifier.verify(hash_obj, signature) def negative_test(self, hash_obj=hash_obj, verifier=verifier, signature=tv.s): self.assertRaises(ValueError, verifier.verify, hash_obj, signature) if tv.result == 'p': setattr(FIPS_PKCS1_Verify_Tests, "test_positive_%d" % count, positive_test) else: setattr(FIPS_PKCS1_Verify_Tests, "test_negative_%d" % count, negative_test)
# David Chaum 1983 提出加密技术运用于现金 from Crypto.Signature import pss from Crypto.Hash import SHA256 from Crypto.PublicKey import RSA from Crypto import Random # sender can create the signatue of a message using their private key message = b'To be signed' key = RSA.importKey(open('../01blockchain explained by picture/i4PyCryptodome/d3private.pem').read()) h = SHA256.new(message) signature = pss.new(key).sign(h) print(signature, type(signature)) print('-' * 20) key = RSA.importKey(open('../01blockchain explained by picture/i4PyCryptodome/d3public.pem').read()) h = SHA256.new(message) verifier = pss.new(key) try: verifier.verify(h, signature) print("The signature is authentic.") except (ValueError, TypeError): print("The signature is not authentic.")
def test_can_sign(self): test_public_key = RSA.generate(1024).publickey() verifier = pss.new(test_public_key) self.assertEqual(verifier.can_sign(), False)
def verify_negative(self, hashmod, message, public_key, salt, signature): prng = PRNG(salt) hashed = hashmod.new(message) verifier = pss.new(public_key, salt_bytes=len(salt), rand_func=prng) self.assertRaises(ValueError, verifier.verify, hashed, signature)
def verify_positive(self, hashmod, message, public_key, salt, signature): prng = PRNG(salt) hashed = hashmod.new(message) verifier = pss.new(public_key, salt_bytes=len(salt), rand_func=prng) verifier.verify(hashed, signature)
def test_can_sign(self): test_private_key = RSA.generate(1024) signer = pss.new(test_private_key) self.assertEqual(signer.can_sign(), True)