def comprobar_firma(mensaje, clave_publica): # Saco la firma (sabemos que es de 256 bytes) firma = mensaje[:256] # Calculo el hash del mensaje h = SHA256.new(mensaje[256:]) # Compruebo si la firma es correcta o no try: pss.new(clave_publica).verify(h, firma) except (ValueError): return False return True
def firmar(mensaje, fichero, path): # Comprobamos si el directorio de ficheros locales existe if not os.path.exists(LF_DIR): os.makedirs(LF_DIR) # Lo creamos si no existe # Abrimos el fichero donde firmaremos nombre = 'sig_' + path fichero_firmado = open(LF_DIR+'/'+nombre, 'wb') # Obtenemos la clave privada del usuario try: key = RSA.import_key(open(fichero, 'rb').read()) except (ValueError, IndexError, TypeError): print('Error parseando la clave a importar') return # Pasamos el texto por la funcion hash SHA256 h = SHA256.new(mensaje) # Obtenemos la firma y la escribimos al comienzo del fichero resultado try: fichero_firmado.write(pss.new(key).sign(h)) except (ValueError): print('Error firmando el mensaje: La clave RSA no es suficientemente larga para el algoritmo hash utilizado') return except (TypeError): print('Error firmando el mensaje: La clave RSA no tiene una mitad privada') return # Escribimos el mensaje original despues de la firma fichero_firmado.write(mensaje) fichero_firmado.close() return nombre
def verify(self, msg: bytes, signature: bytes): _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 stitch_ta(): try: with open(args.sigf, 'r') as sigfile: sig = base64.b64decode(sigfile.read()) except IOError: if not os.path.exists(args.digf): generate_digest() logger.error( 'No signature file found. Please sign\n %s\n' + 'offline and place the signature at \n %s\n' + 'or pass a different location ' + 'using the --sig argument.\n', args.digf, args.sigf) sys.exit(1) else: if args.algo == 'TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256': verifier = pss.new(key) elif args.algo == 'TEE_ALG_RSASSA_PKCS1_V1_5_SHA256': verifier = pkcs1_15.new(key) try: verifier.verify(h, sig) write_image_with_signature(sig) logger.info('Successfully applied signature.') except ValueError: logger.error('Verification failed, ignoring given signature.') sys.exit(1)
def main(): s = clientSetup() # Creates Private & Public Keys key = RSA.generate(2048) private_key = key.export_key() public_key = key.publickey().export_key() writeFile("private.pem", private_key) writeFile("public.pem", public_key) print("Keys Generated") public_key = RSA.import_key(open("public.pem").read()) private_key = RSA.import_key(open("private.pem").read()) # Reads NoWar.dat file message = readFile("NoWar.dat").encode() print("Hashing Message") hash_obj = SHA256.new(message) signature = pss.new(private_key).sign(hash_obj) s.send(signature) confirmation = s.recv(4096).decode() print(confirmation) s.send(message) confirmation = s.recv(4096).decode() print(confirmation) # Closing Socket s.close()
def test_ds4key_sign(self): ''' Challenge signing with DS4Key object directly. ''' ds4key_bytes = base64.b64decode(TEST_DS4KEY) ds4key_io = io.BytesIO(ds4key_bytes) ds4id_expected = ds4key_bytes[:0x310] ds4key = ds4.DS4Key(ds4key_io) challenge = os.urandom(256) response = ds4key.sign_challenge(challenge) resp_bytes = bytes(response) sig = resp_bytes[:0x100] ds4id = resp_bytes[0x100:] self.assertEqual(ds4id.hex(), ds4id_expected.hex(), 'DS4ID mismatch.') ds4key_key = RSA.import_key(TEST_DS4KEY_JUST_KEY) ds4key_pss = pss.new(ds4key_key) sha = SHA256.new(challenge) try: ds4key_pss.verify(sha, sig) except ValueError as e: self.fail(f'Response verification failed. ({str(e)})')
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 rsa_verify(pubkey, received_message, signature): h = SHA384.new(received_message) verifier = pss.new(pubkey) try: verifier.verify(h, base64.b64decode(signature)) return True except ValueError: return False
def checkSignature(message): global KEY_P try: msgSig = str(message[0]) msgHash = SHA256.new(str(message[1])) verifier = pss.new(KEY_P) verifier.verify(msgHash, msgSig) return True except: return False
def verify_sign(self, file_path, sig_file_path): with open(file_path, 'rb') as f, open(sig_file_path, 'rb') as f_sig: key = RSA.import_key(self.public_key) h = SHA256.new(f.read()) verifier = pss.new(key) try: verifier.verify(h, f_sig.read()) return True except (ValueError, TypeError): return False
def encodeMessage(message_dict): #message should be ordered dict global KEY msgData = bson.BSON.encode( message_dict, codec_options=bson.codec_options.CodecOptions( document_class=collections.OrderedDict)) msgHash = SHA256.new(str(msgData)) signer = pss.new(KEY) msgSignature = signer.sign(msgHash) return (msgSignature, msgData)
def sign(fileIn, privKeyPath, signatureOut=None): if not signatureOut: signatureOut = fileIn + '.sign' with open(fileIn, 'rb') as f: data = f.read() with open(privKeyPath, 'rb') as f: privKey = RSA.import_key(f.read()) dataHash = SHA512.new(data) signature = pss.new(privKey).sign(dataHash) with open(signatureOut, 'w') as f: f.write(PEM.encode(signature, 'PKCS1-PSS SIGNATURE'))
def test_verify(self, tv): self._id = "Wycheproof RSA PSS Test #%d (%s)" % (tv.id, tv.comment) hashed_msg = tv.hash_module.new(tv.msg) signer = pss.new(tv.key, mask_func=tv.mgf, salt_bytes=tv.sLen) 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 sign_encrypt_ta(): if not key.has_private(): logger.error('Provided key cannot be used for signing, ' + 'please use offline-signing mode.') sys.exit(1) else: signer = pss.new(key) sig = signer.sign(h) if len(sig) != sig_len: raise Exception( ("Actual signature length is not equal to ", "the computed one: {} != {}").format(len(sig), sig_len)) write_image_with_signature(sig) logger.info('Successfully signed application.')
def verify(fileIn, signaturePath, pubKeyPath): with open(fileIn, 'rb') as f: data = f.read() with open(signaturePath, 'r') as f: signature = PEM.decode(f.read())[0] with open(pubKeyPath, 'rb') as f: pubKey = RSA.import_key(f.read()) fileHash = SHA512.new(data) verifier = pss.new(pubKey) try: verifier.verify(fileHash, signature) return True except (ValueError, TypeError): return False
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 Cryptodome.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 main(): from Cryptodome.Signature import pss from Cryptodome.Hash import SHA256 from Cryptodome.PublicKey import RSA, ECC import os import logging import sys logging.basicConfig() logger = logging.getLogger(os.path.basename(__file__)) args = get_args(logger) with open(args.master_key, 'rb') as f: master_key = RSA.import_key(f.read()) with open(args.tp_key, 'rb') as f: if args.tp_key_type == 'rsa': tp_key = RSA.import_key(f.read()) tp_key_raw = proc_rsa_key(tp_key) elif args.tp_key_type == 'ecdsa': tp_key = ECC.import_key(f.read()) tp_key_raw = proc_ecdsa_key(tp_key) else: logger.error('Invalid key format') sys.exit(1) h = SHA256.new() h.update(tp_key_raw) md = h.digest() if master_key.has_private(): signer = pss.new(master_key) sig = signer.sign(md) with open(args.uuid + '.crt', 'wb') as f: f.write(sig) f.write(tp_key_raw) else: logger.error('Provided key can\'t be used for signing') sys.exit(1)
async def _factory(key, t=None): timestamp = t if t is not None else int(time.time()) pub_key = key.publickey().export_key().decode() # noinspection PyTypeChecker sign = pss.new(key).sign( SHA3_256.new(''.join([ pub_key, str(timestamp) ]).encode()) ).hex() response = await client.post('/create/', json={ "pub_key": pub_key, "timestamp": timestamp, "sign": sign }) assert response.status_code == 201, "Wrong create account status %s" % response.content d = response.json() assert 'account' in d assert 'pub_key' in d return d['account']
def create_ta_cert(): if args.tp_cert: shutil.copy(args.tp_cert, str(args.uuid) + '.cert') else: with open(args.master_key, 'rb') as f: master_key = RSA.import_key(f.read()) if not (master_key.has_private()): logger.error('Provided key can\'t be used for signing') sys.exit(1) if args.tp_key_type == 'ecdsa': raw_key = serialize_ecdsa_key(key) else: raw_key = serialize_rsa_key(key) md = SHA256.new(raw_key) sig = pss.new(master_key).sign(md) with open(str(args.uuid) + '.cert', 'wb') as f: f.write(sig) f.write(raw_key)
def main(): c = serverSetup() c, addr = c.accept() print('Connection from: ' + str(addr)) signature = c.recv(4096) confirmation = "Signature received at bob" c.send(confirmation.encode()) message = c.recv(4096) confirmation = "Message received at bob" c.send(confirmation.encode()) public_key = RSA.import_key(open('public.pem').read()) hash_obj = SHA256.new(message) verifier = pss.new(public_key) try: verifier.verify(hash_obj, signature) print("The signature is authentic.") print(message) except (ValueError, TypeError): print("The signature is not authentic.")
def __init__(self, ds4key_file: BinaryIO) -> None: ds4key = DS4FullKeyBlock() actual = ds4key_file.readinto(ds4key) #type: ignore if actual != ctypes.sizeof(DS4FullKeyBlock): raise ValueError('DS4Key too small.') n = bytes_to_long(bytes(ds4key.identity.modulus)) e = bytes_to_long(bytes(ds4key.identity.exponent)) p = bytes_to_long(bytes(ds4key.private_key.p)) q = bytes_to_long(bytes(ds4key.private_key.q)) dp1 = bytes_to_long(bytes(ds4key.private_key.dp1)) dq1 = bytes_to_long(bytes(ds4key.private_key.dq1)) pq = bytes_to_long(bytes(ds4key.private_key.pq)) d = Integer(e).inverse((p - 1) * (q - 1)) #type: ignore[call-arg] pq_from_pq = Integer(q).inverse(p) #type: ignore[call-arg] dp1_from_pq = Integer(d) % (p - 1) #type: ignore[call-arg] dq1_from_pq = Integer(d) % (q - 1) #type: ignore[call-arg] if Integer(pq) != pq_from_pq or Integer(dp1) != dp1_from_pq or Integer( dq1) != dq1_from_pq: #type: ignore[call-arg] raise ValueError( 'Bad key block (CRT factors inconsistent with P and Q)') # TODO broken type tagging in pycryptodome. Should we fix it upstream? key = RSA.construct((n, e, d, p, q), consistency_check=True) #type: ignore[arg-type] fppub = SHA256.new(key.publickey().exportKey('DER')).hexdigest() fppriv = SHA256.new(key.exportKey('DER')).hexdigest() self._key = key self._pss = pss.new(self._key) self._ds4id = DS4SignedIdentityBlock() self._ds4id.identity = ds4key.identity self._ds4id.sig_identity = ds4key.sig_identity logger.info('DS4Key loaded fingerprint=%s, private_fingerprint=%s', fppub, fppriv)
def test_can_sign(self): test_private_key = RSA.generate(1024) signer = pss.new(test_private_key) self.assertEqual(signer.can_sign(), True)
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)
def test_negative_2(self): key = RSA.import_key(self.rsa_key) h = SHA256.new(self.msg) verifier = pss.new(key, salt_bytes=1000) tag = bytearray(self.tag) self.assertRaises(ValueError, verifier.verify, h, tag)
def test_positive_1(self): key = RSA.import_key(self.rsa_key) h = SHA256.new(self.msg) verifier = pss.new(key) verifier.verify(h, self.tag)
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 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 rsa_sign(key, message): h = SHA384.new(message) signature = pss.new(key).sign(h) return base64.b64encode(signature)
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 sign(self, file_path, password): with open(file_path, 'rb') as fi, open(file_path + SIG_EXTEND, 'wb') as fo: key = self.get_private_key(password) h = SHA256.new(fi.read()) fo.write(pss.new(key).sign(h))
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)