Пример #1
0
def decrypt_message(ciphertext: bytes,
                    private_key: rsa.RSAPrivateKey = PRIVATE_KEY) -> bytes:
    """Decrypt some message encrypted with out public key."""
    return private_key.decrypt(
        ciphertext,
        padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                     algorithm=hashes.SHA256(),
                     label=None))
Пример #2
0
def pk_decrypt(ciphertext: bytes, private_key: rsa.RSAPrivateKey) -> bytes:
    """
    Decrypt an RSAES-OAEP-encrypted message.
    """
    plaintext = private_key.decrypt(
        ciphertext,
        padding.OAEP(padding.MGF1(hashes.SHA1()), hashes.SHA1(), None))
    return plaintext
Пример #3
0
def pk_decrypt(ciphertext: bytes, private_key: rsa.RSAPrivateKey) -> bytes:
    """
    Decrypt an RSAES-OAEP-encrypted message.
    """
    plaintext = private_key.decrypt(ciphertext, padding.OAEP(
            padding.MGF1(hashes.SHA1()),
            hashes.SHA1(),
            None))
    return plaintext
Пример #4
0
    def get_decrypted_envelope_data(self, certificate: x509.Certificate,
                                    key: rsa.RSAPrivateKey) -> bytes:
        """Decrypt the encrypted envelope data:
        
        Decrypt encrypted_key using public key of CA
        encrypted_key is available at content.recipient_infos[x].encrypted_key
        algo is content.recipient_infos[x].key_encryption_algorithm
        at the moment this is RSA
        """
        encap = self.encap_content_info
        ct = encap['content_type'].native
        print(ct)
        recipient_info = encap['content']['recipient_infos'][0]

        encryption_algo = recipient_info.chosen[
            'key_encryption_algorithm'].native
        encrypted_key = recipient_info.chosen['encrypted_key'].native

        assert encryption_algo['algorithm'] == 'rsa'

        plain_key = key.decrypt(
            encrypted_key,
            padding=asympad.PKCS1v15(),
        )

        # Now we have the plain key, we can decrypt the encrypted data
        encrypted_contentinfo = encap['content']['encrypted_content_info']
        print('encrypted content type: {}'.format(
            encrypted_contentinfo['content_type'].native))

        algorithm = encrypted_contentinfo[
            'content_encryption_algorithm']  #: EncryptionAlgorithm
        encrypted_content_bytes = encrypted_contentinfo[
            'encrypted_content'].native

        symkey = None

        if algorithm.encryption_cipher == 'aes':
            symkey = AES(plain_key)
            print('cipher AES')
        elif algorithm.encryption_cipher == 'tripledes':
            symkey = TripleDES(plain_key)
            print('cipher 3DES')
        else:
            print('Dont understand encryption cipher: ',
                  algorithm.encryption_cipher)

        print('key length: ', algorithm.key_length)
        print('enc mode: ', algorithm.encryption_mode)

        cipher = Cipher(symkey,
                        modes.CBC(algorithm.encryption_iv),
                        backend=default_backend())
        decryptor = cipher.decryptor()

        return decryptor.update(encrypted_content_bytes) + decryptor.finalize()
Пример #5
0
def rsa_decrypt(enc_short_message: bytes, private_key: rsa.RSAPrivateKey) -> bytes:
    """ decrypt Optimal Asymmetric Encryption Padding (OAEP)"""
    hash_algorithm = hashes.SHA512 if private_key.key_size >= 2048 else hashes.SHA256
    return private_key.decrypt(
        ciphertext=enc_short_message,
        padding=padding.OAEP(
            mgf=padding.MGF1(algorithm=hash_algorithm()),
            algorithm=hash_algorithm(),
            label=None
        )
    )
Пример #6
0
def _compute(
        ciphertext: bytes,
        key:        rsa.RSAPrivateKey,
        ) -> str:

    plain = key.decrypt(
        ciphertext,
        padding.OAEP(
            mgf=padding.MGF1(algorithm=hashes.SHA1()),
            algorithm=hashes.SHA1(),
            label=None
        )
    )

    return b64encode(sha1(plain).digest()).decode("ascii")
Пример #7
0
def decrypt_smime_content(payload: bytes, key: rsa.RSAPrivateKey) -> bytes:
    content_info = ContentInfo.load(payload)

    assert content_info['content_type'].native == 'enveloped_data'
    content: EnvelopedData = content_info['content']

    matching_recipient = content['recipient_infos'][0]

    # Need to see if we hold the key for any valid recipient.
    # for recipient_info in content['recipient_infos']:
    #     assert recipient_info.name == 'ktri'  # Only support KeyTransRecipientInfo
    #     ktri: KeyTransRecipientInfo = recipient_info.chosen
    #     recipient_id: RecipientIdentifier = ktri['rid']
    #     assert recipient_id.name == 'issuer_and_serial_number'  # Only support IssuerAndSerialNumber
    #     matching_recipient = recipient_info

    encryption_algo = matching_recipient.chosen['key_encryption_algorithm'].native
    encrypted_key = matching_recipient.chosen['encrypted_key'].native

    assert encryption_algo['algorithm'] == 'rsa'

    # Get the content key
    plain_key = key.decrypt(
        encrypted_key,
        padding=padding.PKCS1v15(),
    )

    # Now we have the plain key, we can decrypt the encrypted data
    encrypted_contentinfo = content['encrypted_content_info']

    algorithm: EncryptionAlgorithm = encrypted_contentinfo['content_encryption_algorithm']  #: EncryptionAlgorithm
    encrypted_content_bytes = encrypted_contentinfo['encrypted_content'].native

    symkey = None

    if algorithm.encryption_cipher == 'aes':
        symkey = AES(plain_key)
    elif algorithm.encryption_cipher == 'tripledes':
        symkey = TripleDES(plain_key)
    else:
        print('Dont understand encryption cipher: ', algorithm.encryption_cipher)

    cipher = Cipher(symkey, modes.CBC(algorithm.encryption_iv), backend=default_backend())
    decryptor = cipher.decryptor()

    decrypted_data = decryptor.update(encrypted_content_bytes) + decryptor.finalize()
    return decrypted_data
Пример #8
0
    def hybrid_decrypt(h_data, pk: rsa.RSAPrivateKey) -> bytes:
        """
		This method is the hybrid decrypt outlined in the Tor spec 0.4 section
		:param h_data: The handshake data object of type TapCHData
		:param pk: The RSA private key to decrypt the message with
		:return: The decrypted message in bytes
		"""

        if h_data.SYMKEY is None:
            return_message = "hi"  # pk.decrypt(x["GX1"], padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
            #                          algorithm=hashes.SHA256(), label=None))
        else:
            # Get the params of in bytes form
            gx1 = h_data.GX1
            gx2 = h_data.GX2
            sym_key = h_data.SYMKEY
            padding_bytes = h_data.PADDING
            print(padding_bytes + sym_key + gx1)
            print(sym_key)
            print(gx1)
            print(gx2)

            # Decryption begins
            km1 = pk.decrypt(
                padding_bytes + sym_key + gx1,
                padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()),
                             algorithm=hashes.SHA1(),
                             label=None))
            print(len(km1))
            m1 = km1[len(sym_key):]
            sym_key = km1[0:len(sym_key)]

            nonce = bytes(CryptoConstants.KEY_LEN)
            cipher = Cipher(algorithms.AES(sym_key),
                            modes.CTR(nonce),
                            backend=default_backend())
            decryptor = cipher.decryptor()
            m2 = decryptor.update(gx2) + decryptor.finalize()

            # Return the concatenated message
            return_message = m1 + m2
        return return_message
Пример #9
0
def decrypt(key: rsa.RSAPrivateKey, cypher_text: bytes) -> bytes:
    return key.decrypt(cypher_text, padding)