Example #1
0
    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)
Example #2
0
    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)
Example #3
0
    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)
Example #4
0
def Encrypt(data):
    APPConf = AC()
    return symmetric.aes_cbc_pkcs7_encrypt(APPConf.SecretKey.encode('utf-8'),
                                           data.encode('utf-8'),
                                           APPConf.SecretVI.encode('utf-8'))[1]
Example #5
0
 def encrypt(self, data):
     return crypt_symm.aes_cbc_pkcs7_encrypt(self.salted_key, data, self.iv)[1]
Example #6
0
def encrypt_message(data_to_encrypt, enc_alg, encryption_cert):
    """Function encrypts data and returns the generated ASN.1

    :param data_to_encrypt: A byte string of the data to be encrypted
    
    :param enc_alg: The algorithm to be used for encrypting the data
    
    :param encryption_cert: The certificate to be used for encrypting the data

    :return: A CMS ASN.1 byte string of the encrypted data.    
    """

    enc_alg_list = enc_alg.split('_')
    cipher, key_length, mode = enc_alg_list[0], enc_alg_list[1], enc_alg_list[
        2]
    enc_alg_asn1, encrypted_content = None, None

    # Generate the symmetric encryption key and encrypt the message
    key = util.rand_bytes(int(key_length) // 8)
    if cipher == 'tripledes':
        algorithm_id = '1.2.840.113549.3.7'
        iv, encrypted_content = symmetric.tripledes_cbc_pkcs5_encrypt(
            key, data_to_encrypt, None)
        enc_alg_asn1 = algos.EncryptionAlgorithm({
            'algorithm':
            algorithm_id,
            'parameters':
            cms.OctetString(iv)
        })

    elif cipher == 'rc2':
        algorithm_id = '1.2.840.113549.3.2'
        iv, encrypted_content = symmetric.rc2_cbc_pkcs5_encrypt(
            key, data_to_encrypt, None)
        enc_alg_asn1 = algos.EncryptionAlgorithm({
            'algorithm':
            algorithm_id,
            'parameters':
            algos.Rc2Params({'iv': cms.OctetString(iv)})
        })

    elif cipher == 'rc4':
        algorithm_id = '1.2.840.113549.3.4'
        encrypted_content = symmetric.rc4_encrypt(key, data_to_encrypt)
        enc_alg_asn1 = algos.EncryptionAlgorithm({
            'algorithm': algorithm_id,
        })

    elif cipher == 'aes':
        if key_length == '128':
            algorithm_id = '2.16.840.1.101.3.4.1.2'
        elif key_length == '192':
            algorithm_id = '2.16.840.1.101.3.4.1.22'
        else:
            algorithm_id = '2.16.840.1.101.3.4.1.42'

        iv, encrypted_content = symmetric.aes_cbc_pkcs7_encrypt(
            key, data_to_encrypt, None)
        enc_alg_asn1 = algos.EncryptionAlgorithm({
            'algorithm':
            algorithm_id,
            'parameters':
            cms.OctetString(iv)
        })

    # Encrypt the key and build the ASN.1 message
    encrypted_key = asymmetric.rsa_pkcs1v15_encrypt(encryption_cert, key)

    return cms.ContentInfo({
        'content_type':
        cms.ContentType('enveloped_data'),
        'content':
        cms.EnvelopedData({
            'version':
            cms.CMSVersion('v0'),
            'recipient_infos': [
                cms.KeyTransRecipientInfo({
                    'version':
                    cms.CMSVersion('v0'),
                    'rid':
                    cms.RecipientIdentifier({
                        'issuer_and_serial_number':
                        cms.IssuerAndSerialNumber({
                            'issuer':
                            encryption_cert.asn1['tbs_certificate']['issuer'],
                            'serial_number':
                            encryption_cert.asn1['tbs_certificate']
                            ['serial_number']
                        })
                    }),
                    'key_encryption_algorithm':
                    cms.KeyEncryptionAlgorithm(
                        {'algorithm': cms.KeyEncryptionAlgorithmId('rsa')}),
                    'encrypted_key':
                    cms.OctetString(encrypted_key)
                })
            ],
            'encrypted_content_info':
            cms.EncryptedContentInfo({
                'content_type': cms.ContentType('data'),
                'content_encryption_algorithm': enc_alg_asn1,
                'encrypted_content': encrypted_content
            })
        })
    }).dump()
Example #7
0
def encrypt_message(data_to_encrypt, enc_alg, encryption_cert):
    """Function encrypts data and returns the generated ASN.1

    :param data_to_encrypt: A byte string of the data to be encrypted
    :param enc_alg: The algorithm to be used for encrypting the data
    :param encryption_cert: The certificate to be used for encrypting the data

    :return: A CMS ASN.1 byte string of the encrypted data.
    """

    enc_alg_list = enc_alg.split("_")
    cipher, key_length, _ = enc_alg_list[0], enc_alg_list[1], enc_alg_list[2]

    # Generate the symmetric encryption key and encrypt the message
    key = util.rand_bytes(int(key_length) // 8)
    if cipher == "tripledes":
        algorithm_id = "1.2.840.113549.3.7"
        iv, encrypted_content = symmetric.tripledes_cbc_pkcs5_encrypt(
            key, data_to_encrypt, None)
        enc_alg_asn1 = algos.EncryptionAlgorithm({
            "algorithm":
            algorithm_id,
            "parameters":
            cms.OctetString(iv)
        })

    elif cipher == "rc2":
        algorithm_id = "1.2.840.113549.3.2"
        iv, encrypted_content = symmetric.rc2_cbc_pkcs5_encrypt(
            key, data_to_encrypt, None)
        enc_alg_asn1 = algos.EncryptionAlgorithm({
            "algorithm":
            algorithm_id,
            "parameters":
            algos.Rc2Params({"iv": cms.OctetString(iv)}),
        })

    elif cipher == "rc4":
        algorithm_id = "1.2.840.113549.3.4"
        encrypted_content = symmetric.rc4_encrypt(key, data_to_encrypt)
        enc_alg_asn1 = algos.EncryptionAlgorithm({
            "algorithm": algorithm_id,
        })

    elif cipher == "aes":
        if key_length == "128":
            algorithm_id = "2.16.840.1.101.3.4.1.2"
        elif key_length == "192":
            algorithm_id = "2.16.840.1.101.3.4.1.22"
        else:
            algorithm_id = "2.16.840.1.101.3.4.1.42"

        iv, encrypted_content = symmetric.aes_cbc_pkcs7_encrypt(
            key, data_to_encrypt, None)
        enc_alg_asn1 = algos.EncryptionAlgorithm({
            "algorithm":
            algorithm_id,
            "parameters":
            cms.OctetString(iv)
        })
    elif cipher == "des":
        algorithm_id = "1.3.14.3.2.7"
        iv, encrypted_content = symmetric.des_cbc_pkcs5_encrypt(
            key, data_to_encrypt, None)
        enc_alg_asn1 = algos.EncryptionAlgorithm({
            "algorithm":
            algorithm_id,
            "parameters":
            cms.OctetString(iv)
        })
    else:
        raise AS2Exception("Unsupported Encryption Algorithm")

    # Encrypt the key and build the ASN.1 message
    encrypted_key = asymmetric.rsa_pkcs1v15_encrypt(encryption_cert, key)

    return cms.ContentInfo({
        "content_type":
        cms.ContentType("enveloped_data"),
        "content":
        cms.EnvelopedData({
            "version":
            cms.CMSVersion("v0"),
            "recipient_infos": [
                cms.KeyTransRecipientInfo({
                    "version":
                    cms.CMSVersion("v0"),
                    "rid":
                    cms.RecipientIdentifier({
                        "issuer_and_serial_number":
                        cms.IssuerAndSerialNumber({
                            "issuer":
                            encryption_cert.asn1["tbs_certificate"]["issuer"],
                            "serial_number":
                            encryption_cert.asn1["tbs_certificate"]
                            ["serial_number"],
                        })
                    }),
                    "key_encryption_algorithm":
                    cms.KeyEncryptionAlgorithm(
                        {"algorithm": cms.KeyEncryptionAlgorithmId("rsa")}),
                    "encrypted_key":
                    cms.OctetString(encrypted_key),
                })
            ],
            "encrypted_content_info":
            cms.EncryptedContentInfo({
                "content_type": cms.ContentType("data"),
                "content_encryption_algorithm": enc_alg_asn1,
                "encrypted_content": encrypted_content,
            }),
        }),
    }).dump()