Example #1
0
 def verify(self, message: bytes, signature: bytes, key: rsa.RSAPublicKey):
     try:
         key.verify(signature, message,
                    padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH),
                    hashes.SHA256())
         return True
     except InvalidSignature:
         return False
Example #2
0
    def hybrid_encrypt(message: bytes, pk: rsa.RSAPublicKey) -> TapCHData:
        """
		This method is the hybrid encrypt outlined in the Tor spec 0.4 section
		:param message: The message to be encrypted
		:param pk: The RSA public to encrypt the message with
		:return: The object TapCHData that has the client handshake data
		"""
        # First convert the message to a byte array so that we can slice it etc.
        message = bytearray(message)

        if len(message
               ) <= CryptoConstants.PK_ENC_LEN - CryptoConstants.PK_PAD_LEN:
            # Then encrypt the message using the onion key
            p = pk.encrypt(
                message,
                padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                             algorithm=hashes.SHA256(),
                             label=None))

            # Create the TAP_H_DATA object
            padding_bytes = bytes(CryptoConstants.PK_PAD_LEN)
            tap_h_data = TapCHData(padding_bytes, None, p, None)

        else:
            k = bytearray(os.urandom(CryptoConstants.KEY_LEN))
            m1 = message[0:CryptoConstants.PK_ENC_LEN -
                         CryptoConstants.PK_PAD_LEN - CryptoConstants.KEY_LEN]
            m2 = message[CryptoConstants.PK_ENC_LEN -
                         CryptoConstants.PK_PAD_LEN - CryptoConstants.KEY_LEN:]
            p1 = pk.encrypt(
                bytes(k + m1),
                padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()),
                             algorithm=hashes.SHA1(),
                             label=None))

            nonce = bytes(
                CryptoConstants.KEY_LEN)  # all bytes are 0, nonce is the IV
            cipher = Cipher(algorithms.AES(k),
                            modes.CTR(nonce),
                            backend=default_backend())
            encryptor = cipher.encryptor()
            p2 = encryptor.update(m2) + encryptor.finalize()

            print(p1, len(p1))
            print(p2, len(p2))
            print(m2, len(m2))
            # tap_h_data = TapCHData(bytearray(p1)[CryptoConstants.PK_ENC_LEN - CryptoConstants.PK_PAD_LEN:],
            #                        bytearray(p1)[0:CryptoConstants.KEY_LEN],
            #                        bytearray(p1)[CryptoConstants.KEY_LEN:(CryptoConstants.PK_ENC_LEN - CryptoConstants.PK_PAD_LEN)],
            #                        p2)
            tap_h_data = TapCHData(
                bytearray(p1)[0:CryptoConstants.PK_PAD_LEN],
                bytearray(p1)[CryptoConstants.PK_PAD_LEN:(
                    CryptoConstants.PK_PAD_LEN + CryptoConstants.KEY_LEN)],
                bytearray(p1)[(CryptoConstants.PK_PAD_LEN +
                               CryptoConstants.KEY_LEN):], p2)

        return tap_h_data
Example #3
0
 def verify(sig, data, pkey: rsa.RSAPublicKey):
     """Verify that the signature `sig` is valid for data `data` and public key `pkey`.
     Returns True if the signature is valid, False otherwise."""
     try:
         pkey.verify(sig, data, padding.PKCS1v15(),
                     utils.Prehashed(hashes.MD5()))
     except InvalidSignature:
         return False
     return True
Example #4
0
 def verify(self, key: rsa.RSAPublicKey, msg: bytes, sig: bytes) -> bool:
     """Verify the ``msg` and ``sig`` using ``key``."""
     try:
         key.verify(sig, msg, self.padding, self.hash)
     except cryptography.exceptions.InvalidSignature as error:
         logger.debug(error, exc_info=True)
         return False
     else:
         return True
Example #5
0
File: pfr.py Project: saper/spsdk
def calc_pub_key_hash(public_key: RSAPublicKey, backend: BackendClass = openssl_backend) -> bytes:
    """Calculate a hash out of public key's exponent and modulus."""
    exponent = public_key.public_numbers().e  # type: ignore # MyPy is unable to pickup the class member
    exp_len = math.ceil(exponent.bit_length() / 8)
    exp_bytes = exponent.to_bytes(exp_len, "big")

    modulus = public_key.public_numbers().n  # type: ignore # MyPy is unable to pickup the class member
    mod_len = math.ceil(modulus.bit_length() / 8)
    mod_bytes = modulus.to_bytes(mod_len, "big")

    return backend.hash(mod_bytes + exp_bytes)
Example #6
0
 def verify(self, msg: str, signed: str, public_key: RSAPublicKey) -> bool:
     try:
         public_key.verify(binascii.a2b_base64(signed),
                           msg.encode("ascii"),
                           padding=padding.PSS(
                               mgf=padding.MGF1(hashes.SHA256()),
                               salt_length=padding.PSS.MAX_LENGTH),
                           algorithm=hashes.SHA256())
     except InvalidSignature:
         return False
     return True
Example #7
0
def check_certificate_against_public_key(
    cert: Certificate,
    public_key: RSAPublicKey,
) -> None:
    # Check if the signature of the certificate matches the public key
    public_key.verify(
        cert.signature,
        cert.tbs_certificate_bytes,
        PKCS1v15(),
        SHA256(),
    )
Example #8
0
File: jwt.py Project: jonpet6/STPP
def _verify_bytes(public_key: RSAPublicKey, signature: bytes,
                  data: bytes) -> None:
    """
	Raises
	-------
	cryptography.exceptions.InvalidSignature
	"""
    public_key.verify(
        signature, data,
        padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                    salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256())
Example #9
0
    def hybrid_encrypt(message: bytes, pk: rsa.RSAPublicKey):
        """
        Some specifications will refer to the "legacy hybrid encryption" of a
        byte sequence M with a public key PK.  It is computed as follows:

      1. If the length of M is no more than PK_ENC_LEN-PK_PAD_LEN,
         pad and encrypt M with PK.
      2. Otherwise, generate a KEY_LEN byte random key K.
         Let M1 = the first PK_ENC_LEN-PK_PAD_LEN-KEY_LEN bytes of M,
         and let M2 = the rest of M.
         Pad and encrypt K|M1 with PK.  Encrypt M2 with our stream cipher,
         using the key K.  Concatenate these encrypted values.
        :param message: the message to encrypt
        :param pk: the public RSA key
        :return: the encrypted message
        """
        # This if shouldn't ever be true, because this algorithm is used with diffie hellman 128 bit keys.
        # M will be 128 bits, and adding key and padding to it will always make it more than 128 bits
        if len(message
               ) <= CryptoConstants.PK_ENC_LEN - CryptoConstants.PK_PAD_LEN:
            encrpt_msg = pk.encrypt(
                message,
                padding.OAEP(mgf=padding.MGF1(hashes.SHA1()),
                             algorithm=hashes.SHA1(),
                             label=None))
            padding_bytes = bytes(CryptoConstants.PK_PAD_LEN)
            tap_h_data = "temporary"
            print("[*] We got a shorter message. Weird")
        else:
            # Split the message
            m1 = message[:CryptoConstants.PK_ENC_LEN -
                         CryptoConstants.PK_PAD_LEN - CryptoConstants.KEY_LEN]
            m2 = message[CryptoConstants.PK_ENC_LEN -
                         CryptoConstants.PK_PAD_LEN - CryptoConstants.KEY_LEN:]
            # Generate encryption key for AES
            key = bytearray(os.urandom(CryptoConstants.KEY_LEN))
            m1 = bytes(key + m1)
            # Encrypt first part with RSA
            encrpt_msg1 = pk.encrypt(
                m1,
                padding.OAEP(mgf=padding.MGF1(hashes.SHA1()),
                             algorithm=hashes.SHA1(),
                             label=None))
            nonce = bytes(CryptoConstants.KEY_LEN)
            cipher = Cipher(algorithms.AES(key),
                            modes.CTR(nonce),
                            backend=default_backend())
            # Encrypt second part with AES
            encryptor = cipher.encryptor()
            encrpt_msg2 = encryptor.update(m2) + encryptor.finalize()
            return encrpt_msg1 + encrpt_msg2
Example #10
0
    def assertValidSignature(self, public_key: rsa.RSAPublicKey,
                             signed_base64: str, message: bytes):
        from cryptography.hazmat.primitives import hashes
        from cryptography.hazmat.primitives.asymmetric import padding, utils
        import base64
        import hashlib

        digest = hashlib.sha256(message).digest()

        # si la firma es invalida, este metodo arroja una excepcion
        public_key.verify(base64.b64decode(signed_base64), digest,
                          padding.PKCS1v15(), utils.Prehashed(hashes.SHA256()))

        self.assertTrue(True)
Example #11
0
 def encrypt(self, msg: str, public_key: RSAPublicKey) -> str:
     encrypted = public_key.encrypt(
         msg.encode("ascii"),
         padding=padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                              algorithm=hashes.SHA256(),
                              label=None))
     return binascii.b2a_base64(encrypted).decode("utf-8")
Example #12
0
async def verify_signed_dictionary(
    public_key: rsa.RSAPublicKey,
    signature: bytes,
    dictionary: Dict[str, Any],
) -> None:
    """
    Returns None if success,
    else throws cryptography.exceptions.InvalidSignature

    :param public_key: RSA public_key
    :param signature: the signature of the dictionary
    :param dictionary: the actual dictionary
    :raises VerificationException: If the verification fails
    :return: None
    """
    verifier = public_key.verifier(
        signature,
        padding.PSS(
            mgf=padding.MGF1(hashes.SHA256()),
            salt_length=padding.PSS.MAX_LENGTH,
        ),
        hashes.SHA256(),
    )
    verifier.update(await hash(bencode.encode(dictionary)))
    try:
        verifier.verify()
    except InvalidSignature:
        raise VerificationException()
Example #13
0
    def verify_chain(
        first_pubkey: rsa.RSAPublicKey,
        chain: List["X509Certificate"],
        last_pubkey: rsa.RSAPublicKey,
    ) -> bool:
        """
        tests with the sequence defined by the list, if the chain of certificate is valid for this very certificate.
        In particular, it checks if certificates are valid one by one and then if they chain well two by two in sequence
        
        A proves to B that they are related if B can verify such a chain with the function
        [CertB(PubC1), CertC1(PubC2), ..., CertCn(PubCn+1), CertCn+1(PubA)]

        :first_pubkey in B's pubkey
        """

        if list(chain) == []:
            raise ValueError("Empty list")

        if chain[-1].public_key().public_numbers(
        ) != last_pubkey.public_numbers():
            raise ValueError(
                "The chain does not end with the right certificate")

        pubkey = first_pubkey
        for cert in chain:
            if not X509Certificate.verify(cert, pubkey):
                return False
            pubkey = cert.public_key()
        print("chain of cert is valid")
        return True
Example #14
0
def serialize_pubkey(public_key: rsa.RSAPublicKey) -> bytes:
    """
    Encode an RSA public key into the DER format.
    """
    return public_key.public_bytes(
        serialization.Encoding.DER,
        serialization.PublicFormat.SubjectPublicKeyInfo)
Example #15
0
 def encode_public(
     self, public_key: rsa.RSAPublicKey, f_pub: _FragList
 ) -> None:
     """Write RSA public key"""
     pubn = public_key.public_numbers()
     f_pub.put_mpint(pubn.e)
     f_pub.put_mpint(pubn.n)
Example #16
0
def pk_encrypt(message: bytes, public_key: rsa.RSAPublicKey) -> bytes:
    """
    Encrypt a message using RSAES-OAEP.
    """
    ciphertext = public_key.encrypt(
        message, padding.OAEP(padding.MGF1(hashes.SHA1()), hashes.SHA1(),
                              None))
    return ciphertext
Example #17
0
    def verify_signature(public_key: RSAPublicKey, signature: bytes,
                         data: bytes) -> None:
        """Verfies the supplied signature.

        Args:
            public_key: RSA public key with which the verification is done.
            signature: The signature to verify.
            data: The message that was signed.

        Raises:
            InvalidSignature if signature is not valid.
        """
        public_key.verify(
            signature,
            data,
            padding.PKCS1v15(),
            hashes.SHA256(),
        )
Example #18
0
def rsa_encrypt(public_key: rsa.RSAPublicKey, message: bytes) -> bytes:
    return public_key.encrypt(
        message,
        padding.OAEP(
            mgf=padding.MGF1(algorithm=hashes.SHA256()),
            algorithm=hashes.SHA256(),
            label=None,
        ),
    )
Example #19
0
def pk_encrypt(message: bytes, public_key: rsa.RSAPublicKey) -> bytes:
    """
    Encrypt a message using RSAES-OAEP.
    """
    ciphertext = public_key.encrypt(message, padding.OAEP(
            padding.MGF1(hashes.SHA1()),
            hashes.SHA1(),
            None))
    return ciphertext
Example #20
0
def _generate_rsa_seed(key: rsa.RSAPublicKey, hashAlg: int,
                       label: bytes) -> Tuple[bytes, bytes]:
    halg = _get_digest(hashAlg)
    if halg is None:
        raise ValueError(f"unsupported digest algorithm {hashAlg}")
    seed = secrets.token_bytes(halg.digest_size)
    mgf = padding.MGF1(halg())
    padd = padding.OAEP(mgf, halg(), label)
    enc_seed = key.encrypt(seed, padd)
    return (seed, enc_seed)
Example #21
0
 def verify_message(self, msg: bytes, signature: bytes,
                    public_key: RSAPublicKey) -> bool:
     """
     Checks message signature
     :param msg: message
     :param signature: message's signature
     :param public_key: sender's public key
     :return: true if signature is correct, false otherwise
     """
     try:
         public_key.verify(signature=signature,
                           data=msg,
                           padding=padding.PSS(
                               mgf=padding.MGF1(hashes.SHA256()),
                               salt_length=padding.PSS.MAX_LENGTH),
                           algorithm=hashes.SHA256())
     except InvalidSignature:
         return False
     return True
Example #22
0
def dump_public_key(key: rsa.RSAPublicKey) -> bytes:
    """Dump a public key to PEM format (text)

    :param key: An RSAPrivateKey to dump the public key of
    :return: The dumped bytes of the public key, as PEM
    """
    return key.public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo,
    )
Example #23
0
def rsa_encrypt(short_message: bytes, public_key: rsa.RSAPublicKey) -> bytes:
    """ encrypt Optimal Asymmetric Encryption Padding (OAEP)"""
    hash_algorithm = hashes.SHA512 if public_key.key_size >= 2048 else hashes.SHA256
    return public_key.encrypt(
        plaintext=short_message,
        padding=padding.OAEP(
            mgf=padding.MGF1(algorithm=hash_algorithm()),
            algorithm=hash_algorithm(),
            label=None
        )
    )
Example #24
0
 def encrypt(self, message: bytes, otherkey: rsa.RSAPublicKey):
     signature = self.__privkey.sign(
         message,
         apadding.PSS(mgf=apadding.MGF1(hashes.SHA256()),
                      salt_length=apadding.PSS.MAX_LENGTH), hashes.SHA256())
     ciphertext = otherkey.encrypt(
         message,
         apadding.OAEP(mgf=apadding.MGF1(algorithm=hashes.SHA256()),
                       algorithm=hashes.SHA256(),
                       label=None))
     return signature + ciphertext
Example #25
0
def get_pub_key_pem(public_key: RSAPublicKey) -> str:
    pub_key_pem = public_key.public_bytes(
        serialization.Encoding.PEM,
        serialization.PublicFormat.SubjectPublicKeyInfo).strip()

    pub_key_pem = pub_key_pem.replace(
        b"-----BEGIN PUBLIC KEY-----",
        b"-----BEGIN RSA PUBLIC KEY-----").replace(
            b"-----END PUBLIC KEY-----", b"-----END RSA PUBLIC KEY-----")

    return pub_key_pem.decode("ascii")
Example #26
0
def verify(public_key: rsa.RSAPublicKey, msg: bytes, signature: bytes) -> bool:
    """
    Verifies the authenticity of a signed transmission.

    :param public_key: The public key to verify the signature against.
    :type public_key: :class:`rsa.RSAPublicKey`
    :param msg: The signed message.
    :type msg: `bytes`
    :param signature: The signature.
    :type signature: `bytes`
    :returns: True if the signature was verified, False otherwise.
    :rtype: `bool`
    """
    try:
        public_key.verify(signature, msg, padding.PSS(
            mgf=padding.MGF1(hashes.SHA256()),
            salt_length=padding.PSS.MAX_LENGTH),
            hashes.SHA256())
        return True
    except InvalidSignature:
        return False
Example #27
0
    def verify(cert: "X509Certificate", public_key: rsa.RSAPublicKey) -> bool:
        """
        return weither the certificate is valid or not
        """
        try:
            public_key.verify(
                cert._certificate.signature,
                cert._certificate.tbs_certificate_bytes,
                padding.PKCS1v15(),
                cert._certificate.signature_hash_algorithm,
            )
        except InvalidSignature as e:
            print("InvalidSignature")
            return False

        today = datetime.datetime.today()
        if (cert._certificate.not_valid_after < today
                or cert._certificate.not_valid_before > today):
            print("Certificate out of date")
            return False
        return True
Example #28
0
def _pubkey_to_str(pubkey_object: rsa.RSAPublicKey) -> str:
    """ Converts a public key object to a string """

    pem = pubkey_object.public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo)

    key_str = pem.decode()  # type: str
    key_str = key_str[len(_PUBLIC_BEGIN_TAG):]  # remove being tag
    key_str = key_str[:-(len(_PUBLIC_END_TAG) + 1)]  # remove end tag
    key_str = key_str.replace("\n", "")  # remove new lines

    return key_str
Example #29
0
        def get_rsa_verifier(pub_key: rsa.RSAPublicKey):
            if sigAlgo.signature_algo == 'rsassa_pss':
                sig_algo_params = sigAlgo['parameters']
                assert 'mask_gen_algorithm' in sig_algo_params
                assert 'salt_length' in sig_algo_params

                mgf = sig_algo_params['mask_gen_algorithm']['algorithm'].native
                if 'mgf1' != mgf:
                    raise ValueError(
                        "Invalid mask generation algorithm: {}".format(mgf))

                mgf1_hash_algo = sig_algo_params['mask_gen_algorithm'][
                    'parameters']['algorithm'].native
                mgf1_hash_algo = algo_utils.get_hash_algo_by_name(
                    mgf1_hash_algo)
                return Verifier(lambda: pub_key.verify(
                    signature, message,
                    padding.PSS(mgf=padding.MGF1(mgf1_hash_algo),
                                salt_length=sig_algo_params['salt_length'].
                                native), hash_algo))
            else:
                return Verifier(lambda: pub_key.verify(
                    signature, message, padding.PKCS1v15(), hash_algo))
Example #30
0
def encrypt(pub_key: rsa.RSAPublicKey, msg: str | bytes) -> bytes:
    """
    Encrypt a chat message and return the encrypted string.

    :param pub_key: RSA public key to encrypt the message with.
    :type pub_key: :class:`rsa.RSAPublicKey`
    :param msg: Message to encrypt.
    :type msg: :type:`str`
    :return: Encrypted message.
    :rtype: bytes
    """
    msg = _bytes(msg)
    return pub_key.encrypt(
        msg, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                          algorithm=hashes.SHA256(), label=None))
Example #31
0
def pk_verify(message: bytes, public_key: rsa.RSAPublicKey,
        signature: bytes) -> bool:
    """
    Verify a message signature created with RSASSA-PSS.
    """
    verifier = public_key.verifier(signature,
        padding.PSS(padding.MGF1(hashes.SHA256()), padding.PSS.MAX_LENGTH),
        hashes.SHA256())
    verifier.update(message)

    try:
        verifier.verify()
        return True
    except exceptions.InvalidSignature:
        return False
Example #32
0
def pk_verify(message: bytes, public_key: rsa.RSAPublicKey,
              signature: bytes) -> bool:
    """
    Verify a message signature created with RSASSA-PSS.
    """
    verifier = public_key.verifier(
        signature,
        padding.PSS(padding.MGF1(hashes.SHA256()), padding.PSS.MAX_LENGTH),
        hashes.SHA256())
    verifier.update(message)

    try:
        verifier.verify()
        return True
    except exceptions.InvalidSignature:
        return False
Example #33
0
def serialize_pubkey(public_key: rsa.RSAPublicKey) -> bytes:
    """
    Encode an RSA public key into the DER format.
    """
    return public_key.public_bytes(serialization.Encoding.DER,
            serialization.PublicFormat.SubjectPublicKeyInfo)