Beispiel #1
0
 def verify(self, signature, message, signature_as_digits=True):
     global _CryptoLog
     # if _CryptoLog is None:
     #     _CryptoLog = os.environ.get('CRYPTO_LOG') == '1'
     signature_bytes = signature
     if signature_as_digits:
         signature_bytes = number.long_to_bytes(signature, blocksize=4)
     if not strng.is_bin(signature_bytes):
         raise ValueError('signature must be byte string')
     if not strng.is_bin(message):
         raise ValueError('message must be byte string')
     h = hashes.sha1(message, return_object=True)
     result = False
     try:
         pkcs1_15.new(self.keyObject).verify(h, signature_bytes)
         result = True
     except (
             ValueError,
             TypeError,
     ):
         # do not raise any exception... just return False
         lg.exc('signature=%r message=%r' % (
             signature,
             message,
         ))
     if _Debug:
         if _CryptoLog:
             lg.args(_DebugLevel, result=result, signature=signature)
     return result
Beispiel #2
0
def checkSignature(signature, pubKey, fname="./a.py"):
    h = generateHash(fname=fname)
    try:
        pkcs1_15.new(pubKey).verify(h, signature)
    except:
        return False
    return True
Beispiel #3
0
    def __verify_and_load(path: Path) -> Set[Bug]:
        try:
            if not all([
                    path.exists(),
                    path.joinpath(BugReporter._PUBLIC_KEY).exists(),
                    path.joinpath(BugReporter._SIGNATURE).exists(),
                    path.joinpath(BugReporter._BUGS_FOUND).exists()
            ]):
                return set()

            with path.joinpath(BugReporter._PUBLIC_KEY).open("rb") as pubkey:
                public_key = RSA.import_key(pubkey.read())

            with path.joinpath(BugReporter._SIGNATURE).open("rb") as sig:
                signature = sig.read()

            with path.joinpath(BugReporter._BUGS_FOUND).open("rb") as bf:
                bugs_found = bf.read()

            # Verify that the signature matches bugs found
            h = SHA256.new(bugs_found)
            try:
                pkcs1_15.new(public_key).verify(h, signature)
            except ValueError:
                return set()

            return pickle.loads(bugs_found)
        except Exception:
            return set()
Beispiel #4
0
 def verify(self, message: bytes, signature: bytes) -> bool:
     h = SHA256.new(message)
     try:
         pkcs1_15.new(self.public_key).verify(h, signature) # type: ignore
         return True
     except (ValueError, TypeError):
         return False
Beispiel #5
0
def pycryptodome_rsa(count, loop, keysize):
    key = RSA.generate(keysize)
    message = b'I give my permission to order #4355'
    time_list_sign = []

    for l in range(loop):
        start = time.time()
        for c in range (count):
            h = SHA256.new(message)
            signature = pkcs1_15.new(key).sign(h)
        end = time.time() - start
        # print("["+str(l)+"th pycryptodomex_ecdsa:sign second is "+ str(end) + "/"+str(count)+" signature")
        time_list_sign.append(end)
    ave_sign = numpy.mean(numpy.array(time_list_sign))

    time_list_vrfy = []
    for l in range(loop):
        start = time.time()
        for c in range(count):
            try:
                h = SHA256.new(message)
                pkcs1_15.new(key).verify(h, signature)
            except (ValueError, TypeError):
                print ("The signature is not valid.")
        end = time.time() - start
        # print("["+str(l)+"th pycryptodomex_ecdsa:vrfy second is "+ str(end) + "/"+str(count)+" signature")
        time_list_vrfy.append(end)
    ave_vrfy = numpy.mean(numpy.array(time_list_vrfy))

    print("pycryptodomex_rsa:sign average second is "+ str(ave_sign) + "/"+str(count)+" signature")
    print("pycryptodomex_rsa:vrfy average second is "+ str(ave_vrfy) + "/"+str(count)+" signature")
    return time_list_sign, time_list_vrfy
Beispiel #6
0
 def verify(self, signature, message, signature_as_digits=True):
     signature_bytes = signature
     if signature_as_digits:
         signature_text = strng.to_text(signature)
         signature_int = int(signature_text)
         signature_bytes = number.long_to_bytes(signature_int)
         if signature[0:1] == b'0':
             signature_bytes = b'\x00' + signature_bytes
     if not strng.is_bin(signature_bytes):
         raise ValueError('signature must be byte string')
     if not strng.is_bin(message):
         raise ValueError('message must be byte string')
     h = hashes.sha1(message, return_object=True)
     try:
         pkcs1_15.new(self.keyObject).verify(h, signature_bytes)
         result = True
     except (
             ValueError,
             TypeError,
     ):
         if _Debug:
             lg.exc(
                 msg='signature=%r\nmessage=%r\nsignature_as_digits=%r\n' %
                 (signature, message, signature_as_digits))
         result = False
     return result
Beispiel #7
0
    def authenticate_client(self, client_name, auth, rsa_pub_key=None):
        '''Make sure client's signature is correct.'''

        if rsa_pub_key is None:
            logging.debug('Looking up RSA key in client database...')
            rsa_pub_key = self.client_db.get(client_name)
            logging.debug('Was RSA key found? %s', rsa_pub_key is not None)

        # auth ends up as a dictionary after deserialization...
        auth = jsons.load(auth, Auth)
        hashed = SHA256.new(auth.message.encode())
        key = RSA.import_key(rsa_pub_key)
        try:
            # decode hex signature
            signature = bytes.fromhex(auth.hex_signature)
            pkcs1_15.new(key).verify(hashed, signature)
            logging.debug('Authentication successful!')
            return True
        except (ValueError, TypeError):
            logging.debug('Unable to authenticate client: %s', client_name)
            logging.debug(
                'Data dump: %s', {
                    'client_name': client_name,
                    'auth': auth,
                    'rsa_pub_key': rsa_pub_key,
                    'signature': signature,
                    'hashed': hashed
                })
            return False
Beispiel #8
0
 def verify(self, message: bytes, signature: bytes) -> bool:
     h = SHA256.new(message)
     try:
         pkcs1_15.new(self.public_key).verify(h, signature)  # type: ignore
         return True
     except (ValueError, TypeError):
         return False
Beispiel #9
0
    def verify(self, message, signature, key):
        h = crypto.hashing.Hash()
        hash = h.hash_string(message)

        try:
            pkcs1_15.new(key).verify(hash, signature)
            print("The signature is valid.")
        except (ValueError, TypeError):
            print("The signature is not valid.")
def verify_signature(h, public_key, signature):
    """
    Verify if a given signature is valid for a given public_key and hash
    """
    try:
        pkcs1_15.new(public_key).verify(h, signature)
        return True
    except:
        return False
Beispiel #11
0
def rsa_verify_string_sha1(publickeystr, msg, sig):
    key = RSA.importKey(publickeystr)
    h = SHA1.new(msg)
    try:
        pkcs1_15.new(key).verify(h, sig)
        return True
    except ValueError:
        # Raises ValueError if the signature is wrong
        return False
Beispiel #12
0
def ver(o, s, p):
    hash = SHA256.new(o)

    try:
        pkcs1_15.new(p).verify(hash, s)
    except (ValueError, TypeError):
        return False

    return True
Beispiel #13
0
 def verify(self):
     """
     Check if the signature is valid.
     """
     _hash = SHA_2(self._sha, self._message).hash()
     try:
         pkcs1_15.new(self._rsa.private_key).verify(_hash, self._signature)
         return "Digital signature is valid!"
     except ValueError:
         return "Digital signature is not valid!"
Beispiel #14
0
 def verify(self, signature, message):
     h = SHA1.new(message)
     try:
         signature_int = long(signature)
         signature_bytes = number.long_to_bytes(signature_int)
         pkcs1_15.new(self.keyObject).verify(h, signature_bytes)
         result = True
     except (ValueError, TypeError):
         result = False
     return result
Beispiel #15
0
def verify_signature(message, signature):
    signature = bytes.fromhex(signature)
    print(f'Signature from hex {signature}')
    key = RSA.import_key(
        open('/home/rednik/Development/test-hash-hex/pubkey.pem').read())
    h = SHA256.new(message)
    try:
        pkcs1_15.new(key).verify(h, signature)
        print("The signature is valid.")
    except (ValueError, TypeError):
        print("The signature is not valid.")
Beispiel #16
0
 def checkSignture(self, data, signature, public_key_sender):
     #create Hash of data
     hashed = SHA256.new(data)
     #check against signature of sender
     pubKey = RSA.import_key(public_key_sender)
     try:
         pkcs1_15.new(pubKey).verify(hashed, signature)
         print("[+] signaure correct")
         return True
     except (ValueError, TypeError):
         print("[!] The signature is not valid.")
         return False
Beispiel #17
0
def verify_signature():
    key = RSA.import_key(open(public_key, "rb").read())
    hash_message = SHA256.new(str.encode(message))
    try:
        signature_str = open("signature.txt", "r").read()
        signature_byte = str.encode(signature_str)
        signature = base64.b64decode(signature_byte)
        pkcs1_15.new(key).verify(hash_message, signature)
        print(True)
    except (ValueError, TypeError) as e:
        print(e)
        print(False)
Beispiel #18
0
 def verify(self, signature, message):
     h = SHA1.new(strng.to_bin(message))
     try:
         signature_int = int(signature)
         signature_bytes = number.long_to_bytes(signature_int)
         pkcs1_15.new(self.keyObject).verify(h, signature_bytes)
         result = True
     except (ValueError, TypeError):
         from logs import lg
         lg.exc()
         result = False
     return result
def verifySignature(message, signature):
    print("RECIEVED FROM CLIENT...")
    print("Message: " + shorten(message))
    print("Signature: " + shorten(str(signature)))

    try:
        h = SHA256.new(message.encode('utf-8'))
        pkcs1_15.new(RSA_key).verify(h, signature)
        result = "The signature is valid"
    except ValueError:
        result = "The signature or key is invalid"
    print(result)
    return result
Beispiel #20
0
def gen_and_verifyRSA():
    start = time.time()
    h = SHA256.new(message.encode('utf-8'))
    signature = pkcs1_15.new(RSA_key).sign(h)
    genTime = time.time() - start

    start = time.time()
    h1 = SHA256.new(message.encode('utf-8'))
    try:
        pkcs1_15.new(RSA_key).verify(h1, signature)
    except ValueError:
        print("The signature or key is invalid")
    verifyTime = time.time() - start
    return (genTime, verifyTime)
Beispiel #21
0
def create_signature(message):
    key = RSA.import_key(
        open('/home/rednik/Development/test-hash-hex/privkey.pem').read())
    h = SHA256.new(message)
    signature = pkcs1_15.new(key).sign(h)
    print(f'type of the signature: {type(signature)}')
    return signature
Beispiel #22
0
def sign(mensaje):
    """
        Nombre: sign
        Descripcion: Funcion que obtiene la firma de un mensaje mediante
            PCKS usando la clave privada del emisor (clave.pem).
        Argumentos:
            -mensaje: mensaje a firmar.
        Retorno: firma
    """
    print("-> Generando la firma...", end="")
    # Hacemos hash256 del mensaje
    h = SHA256.new(mensaje)
    # Ciframos con PKCS 1.5 el hash con la clave privada del emisor
    try:
        # Obtenemos la clave privada
        f = open('clave.pem', 'r')
        clave_priv_e = RSA.import_key(f.read())
        f.close()

        # sign puede generar ValueError y TypeError
        firma = pkcs1_15.new(clave_priv_e).sign(h)
        print("OK")
        return firma
    except (ValueError, TypeError):
        print("\nError al firmar.")
        return None
Beispiel #23
0
 def write_signature_value(self, wire: VarBinaryStr, contents: List[VarBinaryStr]) -> int:
     h = SHA256.new()
     for blk in contents:
         h.update(blk)
     signature = pkcs1_15.new(self.key).sign(h)
     wire[:] = signature
     return len(signature)
Beispiel #24
0
 def sign_transaction(self, sender, recipient, amount):
     signer = pkcs1_15.new(
         RSA.import_key(binascii.unhexlify(self.private_key)))
     h = SHA256.new(
         (str(sender) + str(recipient) + str(amount)).encode('utf8'))
     signature = signer.sign(h)
     return binascii.hexlify(signature).decode('ascii')
 def generate_digitalsignature(self,content):#Returns digital signature for server with content
     print("Generating Digital Signature")
     digest = SHA256.new(content.encode())
     signer = pkcs1_15.new(RSA.import_key(self.server_private_key.encode()))
     signature = signer.sign(digest)
     print("Digital Signature created.")
     return signature
Beispiel #26
0
 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)
Beispiel #27
0
def sign_log(log_path, private_key_path, out_path=None):
    """
    sample function to demonstrate how to sign a flight log.
    This complements the verify_flight_log_signature methood
    :param log_path: path to log file to be signed
    :param private_key_path: path to the private key to be used for signing.
    :param out_path: path to save the signed log file -
            defaults to '-signed' added to it's name if no path is specified
    :return: None
    """
    with open(log_path, "rb") as log_obj, open(private_key_path) as key_ob:
        jd = json.loads(log_obj.read())
        rsa_key = RSA.import_key(key_ob.read())
        hashed_logdata = SHA256.new(json.dumps((jd['FlightLog'])).encode())
        log_signature = pkcs1_15.new(rsa_key).sign(hashed_logdata)
        # the signature is encoded in base64 for transport
        enc = base64.b64encode(log_signature)
        # dealing with python's byte string expression
        jd['Signature'] = enc.decode('ascii')
    if out_path:
        save_path = out_path
    else:
        save_path = log_path[:-5] + "-signed.json"
    with open(save_path, 'w') as outfile:
        json.dump(jd, outfile, indent=4)
    return save_path
Beispiel #28
0
 def sign(self, message):
     if not self.keyObject:
         raise ValueError('key object is not exist')
     h = SHA1.new(message)
     signature_bytes = pkcs1_15.new(self.keyObject).sign(h)
     signature_int = number.bytes_to_long(signature_bytes)
     signature = str(signature_int)
     return signature
Beispiel #29
0
 def verifySignature(pubkey: RSA.RsaKey, message: bytes, signature: bytes):
     h = SHA256.new(message)
     verifier = pkcs1_15.new(pubkey)
     try:
         verifier.verify(h, signature)
         return True
     except (ValueError, TypeError):
         return False
Beispiel #30
0
 def signData(self, data):
     #create Hash of data
     hashed = SHA256.new(data)
     #sign data with private key
     private_key = RSA.import_key(self.privatekey)
     signature = pkcs1_15.new(private_key).sign(hashed)
     print("[*] client signed data")
     return signature
Beispiel #31
0
def RSA_sign(plaintext, key):
    ''' Создание цифровой подписи для сообщения plaintext закрытым ключом key
        по стандарту PKCS#1 v1.5 (алгоритм RSA)
    '''
    hash_obj = SHA256.new(plaintext)
    signer = pkcs1_15.new(key)
    signature = signer.sign(hash_obj)
    return signature
Beispiel #32
0
 def test_verify(self, tv):
     self._id = "Wycheproof RSA PKCS$#1 Test #" + str(tv.id)
     
     hashed_msg = tv.hash_module.new(tv.msg)
     signer = pkcs1_15.new(tv.key)
     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 runTest(self):

        key = RSA.generate(1024)
        signer = pkcs1_15.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)
Beispiel #34
0
 def sign(self, message: bytes) -> bytes:
     self.assert_initialized()
     h = SHA256.new(message)
     return pkcs1_15.new(self.private_key).sign(h) # type: ignore
                                 { 'shaalg' : lambda x: x,
                                   'd' : lambda x: int(x),
                                   'result' : lambda x: x })


for count, tv in enumerate(test_vectors_verify):
    if isinstance(tv, basestring):
        continue
    if hasattr(tv, "n"):
        modulus = tv.n
        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])
    verifier = pkcs1_15.new(public_key)

    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 == 'f':
        setattr(FIPS_PKCS1_Verify_Tests, "test_negative_%d" % count, negative_test)
    else:
        setattr(FIPS_PKCS1_Verify_Tests, "test_positive_%d" % count, positive_test)


class FIPS_PKCS1_Sign_Tests(unittest.TestCase):
 def runTest(self):
     verifier = pkcs1_15.new(RSA.importKey(self.rsakey))
     hashed = SHA1.new(self.msg)
     verifier.verify(hashed, self.signature)
 def test_can_sign(self):
     test_public_key = RSA.generate(1024).publickey()
     verifier = pkcs1_15.new(test_public_key)
     self.assertEqual(verifier.can_sign(), False)
 def test_can_sign(self):
     test_private_key = RSA.generate(1024)
     signer = pkcs1_15.new(test_private_key)
     self.assertEqual(signer.can_sign(), True)
def new(rsa_key):
    pkcs1 = pkcs1_15.new(rsa_key)
    pkcs1._verify = pkcs1.verify
    pkcs1.verify = types.MethodType(_pycrypto_verify, pkcs1)
    return pkcs1