def test_demo_plugin(): with_plugin_cfg = CertomancerConfig.from_file('tests/data/with-plugin.yml', 'tests/data') with_plugin_app = Animator(AnimatorArchStore(with_plugin_cfg.pki_archs), with_web_ui=False) client = Client(with_plugin_app, Response) # make the endpoint encrypt something endpoint = '/testing-ca/plugin/encrypt-echo/test-endpoint' payload = b'test test test' response = client.post(endpoint, data=payload) # decrypt it env_data = cms.ContentInfo.load(response.data)['content'] arch = with_plugin_cfg.get_pki_arch(ArchLabel('testing-ca')) key = arch.key_set.get_private_key(KeyLabel('signer1')) ktri = env_data['recipient_infos'][0].chosen encrypted_key = ktri['encrypted_key'].native decrypted_key = asymmetric.rsa_pkcs1v15_decrypt( asymmetric.load_private_key(key.dump()), encrypted_key) eci = env_data['encrypted_content_info'] cea = eci['content_encryption_algorithm'] assert cea['algorithm'].native == 'aes256_cbc' iv = cea['parameters'].native encrypted_content_bytes = eci['encrypted_content'].native decrypted_payload = symmetric.aes_cbc_pkcs7_decrypt( decrypted_key, encrypted_content_bytes, iv) assert decrypted_payload == payload
def decrypt_message(encrypted_data, decryption_key): """Function parses an ASN.1 encrypted message and extracts/decrypts the original message. :param encrypted_data: A CMS ASN.1 byte string containing the encrypted data. :param decryption_key: The key to be used for decrypting the data. :return: A byte string containing the decrypted original message. """ cms_content = cms.ContentInfo.load(encrypted_data) cipher, decrypted_content = None, None if cms_content['content_type'].native == 'enveloped_data': recipient_info = cms_content['content']['recipient_infos'][0].parse() key_enc_alg = recipient_info['key_encryption_algorithm'][ 'algorithm'].native encrypted_key = recipient_info['encrypted_key'].native if key_enc_alg == 'rsa': try: key = asymmetric.rsa_pkcs1v15_decrypt(decryption_key[0], encrypted_key) except Exception: raise DecryptionError( 'Failed to decrypt the payload: Could not extract decryption key.' ) alg = cms_content['content']['encrypted_content_info'][ 'content_encryption_algorithm'] encapsulated_data = cms_content['content'][ 'encrypted_content_info']['encrypted_content'].native try: if alg['algorithm'].native == '1.2.840.113549.3.4': # This is RC4 decrypted_content = symmetric.rc4_decrypt( key, encapsulated_data) elif alg.encryption_cipher == 'tripledes': cipher = 'tripledes_192_cbc' decrypted_content = symmetric.tripledes_cbc_pkcs5_decrypt( key, encapsulated_data, alg.encryption_iv) elif alg.encryption_cipher == 'aes': decrypted_content = symmetric.aes_cbc_pkcs7_decrypt( key, encapsulated_data, alg.encryption_iv) elif alg.encryption_cipher == 'rc2': decrypted_content = symmetric.rc2_cbc_pkcs5_decrypt( key, encapsulated_data, alg['parameters']['iv'].native) else: raise AS2Exception('Unsupported Encryption Algorithm') except Exception as e: raise DecryptionError( 'Failed to decrypt the payload: {}'.format(e)) else: raise AS2Exception('Unsupported Encryption Algorithm') else: raise DecryptionError('Encrypted data not found in ASN.1 ') return cipher, decrypted_content
def test_demo_plugin(requests_mock): with_plugin_cfg = CertomancerConfig.from_file('tests/data/with-plugin.yml', 'tests/data') arch = with_plugin_cfg.get_pki_arch(ArchLabel('testing-ca')) illusionist.Illusionist(pki_arch=arch).register(requests_mock) importlib.import_module('example_plugin.encrypt_echo') # make the endpoint encrypt something endpoint = 'http://test.test/testing-ca/plugin/encrypt-echo/test-endpoint' payload = b'test test test' response = requests.post(endpoint, data=payload) # decrypt it env_data = cms.ContentInfo.load(response.content)['content'] key = arch.key_set.get_private_key(KeyLabel('signer1')) ktri = env_data['recipient_infos'][0].chosen encrypted_key = ktri['encrypted_key'].native decrypted_key = asymmetric.rsa_pkcs1v15_decrypt( asymmetric.load_private_key(key.dump()), encrypted_key) eci = env_data['encrypted_content_info'] cea = eci['content_encryption_algorithm'] assert cea['algorithm'].native == 'aes256_cbc' iv = cea['parameters'].native encrypted_content_bytes = eci['encrypted_content'].native decrypted_payload = symmetric.aes_cbc_pkcs7_decrypt( decrypted_key, encrypted_content_bytes, iv) assert decrypted_payload == payload
def decrypt_message(encrypted_data, decryption_key): """Function parses an ASN.1 encrypted message and extracts/decrypts the original message. :param encrypted_data: A CMS ASN.1 byte string containing the encrypted data. :param decryption_key: The key to be used for decrypting the data. :return: A byte string containing the decrypted original message. """ cms_content = cms.ContentInfo.load(encrypted_data) cipher, decrypted_content = None, None if cms_content["content_type"].native == "enveloped_data": recipient_info = cms_content["content"]["recipient_infos"][0].parse() key_enc_alg = recipient_info["key_encryption_algorithm"][ "algorithm"].native encrypted_key = recipient_info["encrypted_key"].native if cms.KeyEncryptionAlgorithmId( key_enc_alg) == cms.KeyEncryptionAlgorithmId("rsa"): try: key = asymmetric.rsa_pkcs1v15_decrypt(decryption_key[0], encrypted_key) except Exception: raise DecryptionError( "Failed to decrypt the payload: Could not extract decryption key." ) alg = cms_content["content"]["encrypted_content_info"][ "content_encryption_algorithm"] encapsulated_data = cms_content["content"][ "encrypted_content_info"]["encrypted_content"].native try: if alg["algorithm"].native == "rc4": decrypted_content = symmetric.rc4_decrypt( key, encapsulated_data) elif alg.encryption_cipher == "tripledes": cipher = "tripledes_192_cbc" decrypted_content = symmetric.tripledes_cbc_pkcs5_decrypt( key, encapsulated_data, alg.encryption_iv) elif alg.encryption_cipher == "aes": decrypted_content = symmetric.aes_cbc_pkcs7_decrypt( key, encapsulated_data, alg.encryption_iv) elif alg.encryption_cipher == "rc2": decrypted_content = symmetric.rc2_cbc_pkcs5_decrypt( key, encapsulated_data, alg["parameters"]["iv"].native) else: raise AS2Exception("Unsupported Encryption Algorithm") except Exception as e: raise DecryptionError( "Failed to decrypt the payload: {}".format(e)) else: raise AS2Exception("Unsupported Encryption Algorithm") else: raise DecryptionError("Encrypted data not found in ASN.1 ") return cipher, decrypted_content
def decrypt(self, data): try: return crypt_symm.aes_cbc_pkcs7_decrypt(self.salted_key, data, self.iv) except OSError as error: if str(error).startswith("error:06065064"): raise AttributeError( "Could not decrypt the current data with given key. (possible wrong key)" ) from error else: raise error
def test_aes_256_encrypt_decrypt(self): key = util.rand_bytes(32) data = b'This is data to encrypt' iv, ciphertext = symmetric.aes_cbc_pkcs7_encrypt(key, data, None) self.assertNotEqual(data, ciphertext) self.assertEqual(byte_cls, type(ciphertext)) plaintext = symmetric.aes_cbc_pkcs7_decrypt(key, ciphertext, iv) self.assertEqual(data, plaintext)
def test_terrible_hybrid_file_encryption_app(self): # Proof of concept code only! import io from oscrypto.asymmetric import load_public_key, rsa_pkcs1v15_encrypt from oscrypto.symmetric import ( aes_cbc_pkcs7_encrypt, aes_cbc_pkcs7_decrypt, ) # A key we generated earlier self.session.generate_keypair(KeyType.RSA, 1024) pub = self.session.get_key(key_type=KeyType.RSA, object_class=ObjectClass.PUBLIC_KEY) pub = load_public_key(encode_rsa_public_key(pub)) key = self.session.generate_random(256) iv = self.session.generate_random(128) source = b'This is my amazing file' with io.BytesIO() as dest: # Write a 128-byte header containing our key and our IV # strictly speaking we don't need to keep the IV secure but # we may as well. # # FIXME: Because this is RSA 1.5, we should fill the rest of the # frame with nonsense self.assertEqual(dest.write(rsa_pkcs1v15_encrypt(pub, key + iv)), 128) _, ciphertext = aes_cbc_pkcs7_encrypt(key, source, iv) dest.write(ciphertext) # Time passes dest.seek(0) # Look up our private key priv = self.session.get_key(key_type=KeyType.RSA, object_class=ObjectClass.PRIVATE_KEY) # Read the header header = dest.read(priv.key_length // 8) header = priv.decrypt(header, mechanism=Mechanism.RSA_PKCS) # The first 32 bytes is our key key, header = header[:32], header[32:] # The next 16 bytes is the IV iv = header[:16] # We can ignore the rest plaintext = aes_cbc_pkcs7_decrypt(key, dest.read(), iv) self.assertEqual(source, plaintext)
def Decrypt(data): APPConf = AC() return symmetric.aes_cbc_pkcs7_decrypt( APPConf.SecretKey.encode('utf-8'), data, APPConf.SecretVI.encode('utf-8')).decode('utf-8')