Python Crypto.Cipher.PKCS1_OAEP.new() Examples

The following are 30 code examples of Crypto.Cipher.PKCS1_OAEP.new(). 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.Cipher.PKCS1_OAEP , or try the search function .
Example #1
Source File: keybag.py    From pyaff4 with Apache License 2.0 6 votes vote down vote up
def create(vek, keySizeBytes, certificatePath):
        #print("VEK: " + str(binascii.hexlify(vek)))
        publicKeyPem = open(certificatePath).read()
        publicKey = RSA.importKey(publicKeyPem)
        # Convert from PEM to DER

        lines = publicKeyPem.replace(" ", '').split()
        publicKeyDer = binascii.a2b_base64(''.join(lines[1:-1]))

        cert = x509.load_pem_x509_certificate(SmartStr(publicKeyPem), default_backend())
        subjectName = cert.subject.rfc4514_string()
        serial = cert.serial_number

        cipher = PKCS1_OAEP.new(key=publicKey, hashAlgo=SHA256, mgfunc=lambda x, y: pss.MGF1(x, y, SHA1))
        wrapped_key = cipher.encrypt(vek)
        #print("WrappedKey: " + str(binascii.hexlify(wrapped_key)))

        return CertEncryptedKeyBag(subjectName, serial, keySizeBytes, wrapped_key) 
Example #2
Source File: test_crypto.py    From pyaff4 with Apache License 2.0 6 votes vote down vote up
def testDecrypt(self):

        g = rdflib.Graph()
        g.parse(data=keybagturtle, format="turtle")
        kb = keybag.PasswordWrappedKeyBag.load(g)

        key = "password"
        kek = digest.pbkdf2_hmac("sha256", key, kb.salt, kb.iterations, kb.keySizeBytes);
        vek = aes_unwrap_key(kek, kb.wrappedKey)

        key1 = vek[0:16]
        key2 = vek[16:]
        tweak = codecs.decode('00', 'hex')

        cipher = python_AES.new((key1, key2), python_AES.MODE_XTS)
        text = cipher.decrypt(target_ciphertext, tweak)

        self.assertEqual(src[0:len(src)], text[0:len(src)]) 
Example #3
Source File: test_pkcs1_oaep.py    From earthengine with MIT License 6 votes vote down vote up
def testEncrypt1(self):
                # Verify encryption using all test vectors
                for test in self._testData:
                        # Build the key
                        comps = [ long(rws(test[0][x]),16) for x in ('n','e') ]
                        key = RSA.construct(comps)
                        # RNG that takes its random numbers from a pool given
                        # at initialization
                        class randGen:
                            def __init__(self, data):
                                self.data = data
                                self.idx = 0
                            def __call__(self, N):
                                r = self.data[self.idx:N]
                                self.idx += N
                                return r
                        # The real test
                        key._randfunc = randGen(t2b(test[3]))
                        cipher = PKCS.new(key, test[4])
                        ct = cipher.encrypt(t2b(test[1]))
                        self.assertEqual(ct, t2b(test[2])) 
Example #4
Source File: test_pkcs1_oaep.py    From earthengine with MIT License 6 votes vote down vote up
def testEncryptDecrypt1(self):
                # Helper function to monitor what's requested from RNG
                global asked
                def localRng(N):
                    global asked
                    asked += N
                    return self.rng(N)
                # Verify that OAEP is friendly to all hashes
                for hashmod in (MD2,MD5,SHA1,SHA256,RIPEMD):
                    # Verify that encrypt() asks for as many random bytes
                    # as the hash output size
                    asked = 0
                    pt = self.rng(40)
                    self.key1024._randfunc = localRng
                    cipher = PKCS.new(self.key1024, hashmod)
                    ct = cipher.encrypt(pt)
                    self.assertEqual(cipher.decrypt(ct), pt)
                    self.failUnless(asked > hashmod.digest_size) 
Example #5
Source File: utils.py    From snapy with MIT License 6 votes vote down vote up
def encryptPassword(email, password):
    gdpk = "AAAAgMom/1a/v0lblO2Ubrt60J2gcuXSljGFQXgcyZWveWLEwo6prwgi3iJIZdodyhKZQrNWp5nKJ3srRXcUW+F1BD3baEVGcmEgqaLZUNBjm057pKRI16kB0YppeGx5qIQ5QjKzsR8ETQbKLNWgRY0QRNVz34kMJR3P/LgHax/6rmf5AAAAAwEAAQ=="
    binaryKey = b64decode(gdpk).encode('hex')
    
    half = binaryKey[8:264]
    modulus = long(half, 16)
    
    half = binaryKey[272:278]
    exponent = long(half, 16)
    
    sha1hash = sha1(b64decode(gdpk)).digest()
    signature = "00" + sha1hash[:4].encode('hex')
    
    key = RSA.construct((modulus, exponent))
    cipher = PKCS1_OAEP.new(key)
    plain = email + "\x00" + password
    encrypted = cipher.encrypt(plain).encode('hex')
    ste = signature + encrypted
    output = unhexlify(ste)
    
    encryptedPassword = b64encode(output).encode('ascii').replace("+","-").replace("/","_")
    return encryptedPassword 
Example #6
Source File: test_pkcs1_oaep.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def testEncrypt1(self):
                # Verify encryption using all test vectors
                for test in self._testData:
                        # Build the key
                        comps = [ long(rws(test[0][x]),16) for x in ('n','e') ]
                        key = RSA.construct(comps)
                        # RNG that takes its random numbers from a pool given
                        # at initialization
                        class randGen:
                            def __init__(self, data):
                                self.data = data
                                self.idx = 0
                            def __call__(self, N):
                                r = self.data[self.idx:N]
                                self.idx += N
                                return r
                        # The real test
                        key._randfunc = randGen(t2b(test[3]))
                        cipher = PKCS.new(key, test[4])
                        ct = cipher.encrypt(t2b(test[1]))
                        self.assertEqual(ct, t2b(test[2])) 
Example #7
Source File: test_pkcs1_oaep.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def testEncryptDecrypt1(self):
                # Helper function to monitor what's requested from RNG
                global asked
                def localRng(N):
                    global asked
                    asked += N
                    return self.rng(N)
                # Verify that OAEP is friendly to all hashes
                for hashmod in (MD2,MD5,SHA1,SHA256,RIPEMD):
                    # Verify that encrypt() asks for as many random bytes
                    # as the hash output size
                    asked = 0
                    pt = self.rng(40)
                    self.key1024._randfunc = localRng
                    cipher = PKCS.new(self.key1024, hashmod)
                    ct = cipher.encrypt(pt)
                    self.assertEqual(cipher.decrypt(ct), pt)
                    self.failUnless(asked > hashmod.digest_size) 
Example #8
Source File: test_encryption.py    From tbk with GNU General Public License v3.0 6 votes vote down vote up
def test_encrypt(self, sign_message, encrypt_message, encrypt_key, get_key, get_iv):
        message = Random.new().read(2000)
        encryption = Encryption(self.sender_key, self.recipient_key)
        sender_key_bytes = int(self.sender_key.publickey().n.bit_length() / 8)
        encrypt_message.return_value = Random.new().read(len(message))
        encrypt_key.return_value = Random.new().read(sender_key_bytes)
        get_iv.return_value = Random.new().read(16)

        encrypted_message = encryption.encrypt(message)

        data = base64.b64decode(encrypted_message)
        iv = data[0:16]
        encrypted_key = data[16:(16 + sender_key_bytes)]
        encrypted_message = data[(16 + sender_key_bytes):]

        self.assertEqual(encrypt_message.return_value, encrypted_message)
        self.assertEqual(encrypt_key.return_value, encrypted_key)
        self.assertEqual(get_iv.return_value, iv)
        encrypt_key.assert_called_once_with(get_key.return_value)
        encrypt_message.assert_called_once_with(
            sign_message.return_value, message, get_key.return_value, get_iv.return_value
        )
        sign_message.assert_called_once_with(message) 
Example #9
Source File: test_encryption.py    From tbk with GNU General Public License v3.0 6 votes vote down vote up
def test_decrypt(self, verify, get_message, get_signature, get_decrypted_message, get_key, get_iv, hexlify):
        decryption = Decryption(self.recipient_key, self.sender_key)
        raw = Random.new().read(2000)
        encrypted = base64.b64encode(raw)
        message = get_message.return_value
        signature = get_signature.return_value
        hexlify_signature = hexlify.return_value
        decrypted_message = get_decrypted_message.return_value
        iv = get_iv.return_value
        key = get_key.return_value
        verify.return_value = True

        returned_message, returned_signature = decryption.decrypt(encrypted)

        self.assertEqual(message, returned_message)
        self.assertEqual(hexlify_signature, returned_signature)
        get_message.assert_called_once_with(decrypted_message)
        get_decrypted_message.assert_called_once_with(iv, key, raw)
        get_iv.assert_called_once_with(raw)
        get_key.assert_called_once_with(raw)
        get_signature.assert_called_once_with(decrypted_message)
        verify.assert_called_once_with(signature, message)
        hexlify.assert_called_once_with(signature) 
Example #10
Source File: main.py    From cryptovenom with GNU General Public License v3.0 6 votes vote down vote up
def signRSA(message, privatekey, hashAlg):

    global hash1
    hash1 = hashAlg
    signer = PKCS1_v1_5.new(privatekey)
    if (hash1 == "SHA-512"):
        digest = SHA512.new()
    elif (hash1 == "SHA-384"):
        digest = SHA384.new()
    elif (hash1 == "SHA-256"):
        digest = SHA256.new()
    elif (hash1 == "SHA-1"):
        digest = SHA.new()
    else:
        digest = MD5.new()
    digest.update(message)
    return signer.sign(digest) 
Example #11
Source File: crypto.py    From aliyun-oss-python-sdk with MIT License 6 votes vote down vote up
def __init__(self, key_pair, passphrase=None, cipher=utils.AESCTRCipher(), mat_desc=None):

        super(RsaProvider, self).__init__(cipher=cipher, mat_desc=mat_desc)
        self.wrap_alg = headers.RSA_NONE_PKCS1Padding_WRAP_ALGORITHM

        if key_pair and not isinstance(key_pair, dict):
            raise ClientError('Invalid type, the type of key_pair must be dict!')

        try:
            if 'public_key' in key_pair:
                self.__encrypt_obj = PKCS1_v1_5.new(RSA.importKey(key_pair['public_key'], passphrase=passphrase))

            if 'private_key' in key_pair:
                self.__decrypt_obj = PKCS1_v1_5.new(RSA.importKey(key_pair['private_key'], passphrase=passphrase))
        except (ValueError, TypeError) as e:
            raise ClientError(str(e)) 
Example #12
Source File: keybag.py    From pyaff4 with Apache License 2.0 5 votes vote down vote up
def unwrap_key(self, privateKey):
        key = RSA.importKey(open(privateKey).read())
        cipher = PKCS1_OAEP.new(key=key, hashAlgo=SHA256, mgfunc=lambda x, y: pss.MGF1(x, y, SHA1))
        vek = cipher.decrypt(self.wrappedKey)
        #print("VEK: " + str(binascii.hexlify(vek)))
        return vek 
Example #13
Source File: test_crypto.py    From pyaff4 with Apache License 2.0 5 votes vote down vote up
def testEncrypt(self):
        vek = binascii.unhexlify("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f")
        plaintext = src + b'\x00' * (512-len(src))

        key1 = vek[0:16]
        key2 = vek[16:]

        tweak = codecs.decode('00', 'hex')

        cipher = python_AES.new((key1,key2), python_AES.MODE_XTS)
        ciphertext = cipher.encrypt(plaintext, tweak)

        self.assertEqual(target_ciphertext, ciphertext) 
Example #14
Source File: test_crypto.py    From pyaff4 with Apache License 2.0 5 votes vote down vote up
def testWrap(self):
        keysize = 0x20   # in bytes
        key = "password"
        iterations = 147256
        saltSize = 16
        salt = binascii.unhexlify("000102030405060708090a0b0c0d0e0f")


        #hhh = hashlib.pbkdf2_hmac("sha256", key.encode(), salt, iterations, keysize);
        #print(len(hhh))
        #print(binascii.hexlify(hhh))

        kek = digest.pbkdf2_hmac("sha256", key, salt, iterations, keysize);
        print(binascii.hexlify(kek))

        #h = pbkdf2_sha256.encrypt(key, rounds=iterations, salt_size=saltSize)
        # print(h)



        vek = binascii.unhexlify("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f")
        print(len(vek))
        wrapped_key= aes_wrap_key(kek, vek)
        print(binascii.hexlify(wrapped_key))

        plaintext = src + b'\x00' * (512-len(src))

        #msg = dict_xts_aes['msg%i' % i].decode('hex')
        #key = (dict_xts_aes['key1_%i' % i].decode('hex'), dict_xts_aes['key2_%i' % i].decode('hex'))
        key1 = vek[0:16]
        key2 = vek[16:]
        #cip = dict_xts_aes['cip%i' % i].decode('hex')
        #n = dict_xts_aes['n%i' % i].decode('hex')
        tweak = codecs.decode('00', 'hex')
        print(len(tweak))
        cipher = python_AES.new((key1,key2), python_AES.MODE_XTS)
        ciphertext = cipher.encrypt(plaintext, tweak)

        print(len(ciphertext))
        print(binascii.hexlify(ciphertext)) 
Example #15
Source File: test_pkcs1_oaep.py    From earthengine with MIT License 5 votes vote down vote up
def rws(t):
    """Remove white spaces, tabs, and new lines from a string"""
    for c in ['\n', '\t', ' ']:
        t = t.replace(c,'')
    return t 
Example #16
Source File: test_pkcs1_oaep.py    From earthengine with MIT License 5 votes vote down vote up
def setUp(self):
                self.rng = Random.new().read
                self.key1024 = RSA.generate(1024, self.rng)

        # List of tuples with test data for PKCS#1 OAEP
        # Each tuple is made up by:
        #       Item #0: dictionary with RSA key component
        #       Item #1: plaintext
        #       Item #2: ciphertext
        #       Item #3: random data (=seed)
        #       Item #4: hash object 
Example #17
Source File: test_pkcs1_oaep.py    From earthengine with MIT License 5 votes vote down vote up
def testEncrypt2(self):
                # Verify that encryption fails if plaintext is too long
                pt = '\x00'*(128-2*20-2+1)
                cipher = PKCS.new(self.key1024)
                self.assertRaises(ValueError, cipher.encrypt, pt) 
Example #18
Source File: test_pkcs1_oaep.py    From earthengine with MIT License 5 votes vote down vote up
def testDecrypt1(self):
                # Verify decryption using all test vectors
                for test in self._testData:
                        # Build the key
                        comps = [ long(rws(test[0][x]),16) for x in ('n','e','d') ]
                        key = RSA.construct(comps)
                        # The real test
                        cipher = PKCS.new(key, test[4])
                        pt = cipher.decrypt(t2b(test[2]))
                        self.assertEqual(pt, t2b(test[1])) 
Example #19
Source File: test_pkcs1_oaep.py    From earthengine with MIT License 5 votes vote down vote up
def testEncryptDecrypt2(self):
                # Verify that OAEP supports labels
                pt = self.rng(35)
                xlabel = self.rng(22)
                cipher = PKCS.new(self.key1024, label=xlabel)
                ct = cipher.encrypt(pt)
                self.assertEqual(cipher.decrypt(ct), pt) 
Example #20
Source File: test_pkcs1_oaep.py    From earthengine with MIT License 5 votes vote down vote up
def testEncryptDecrypt3(self):
                # Verify that encrypt() uses the custom MGF
                global mgfcalls
                # Helper function to monitor what's requested from MGF
                def newMGF(seed,maskLen):
                    global mgfcalls
                    mgfcalls += 1
                    return bchr(0x00)*maskLen
                mgfcalls = 0
                pt = self.rng(32)
                cipher = PKCS.new(self.key1024, mgfunc=newMGF)
                ct = cipher.encrypt(pt)
                self.assertEqual(mgfcalls, 2)
                self.assertEqual(cipher.decrypt(ct), pt) 
Example #21
Source File: default_crypto.py    From plugin.video.netflix with MIT License 5 votes vote down vote up
def load_crypto_session(self, msl_data=None):
        try:
            self.encryption_key = base64.standard_b64decode(
                msl_data['encryption_key'])
            self.sign_key = base64.standard_b64decode(
                msl_data['sign_key'])
            if not self.encryption_key or not self.sign_key:
                raise MSLError('Missing encryption_key or sign_key')
            self.rsa_key = RSA.importKey(
                base64.standard_b64decode(msl_data['rsa_key']))
        except Exception:  # pylint: disable=broad-except
            common.debug('Generating new RSA keys')
            self.rsa_key = RSA.generate(2048)
            self.encryption_key = None
            self.sign_key = None 
Example #22
Source File: default_crypto.py    From plugin.video.netflix with MIT License 5 votes vote down vote up
def encrypt(self, plaintext, esn):
        """
        Encrypt the given Plaintext with the encryption key
        :param plaintext:
        :return: Serialized JSON String of the encryption Envelope
        """
        init_vector = get_random_bytes(16)
        cipher = AES.new(self.encryption_key, AES.MODE_CBC, init_vector)
        ciphertext = base64.standard_b64encode(
            cipher.encrypt(Padding.pad(plaintext.encode('utf-8'), 16))).decode('utf-8')
        encryption_envelope = {
            'ciphertext': ciphertext,
            'keyid': '_'.join((esn, str(self.sequence_number))),
            'sha256': 'AA==',
            'iv': base64.standard_b64encode(init_vector).decode('utf-8')
        }
        return json.dumps(encryption_envelope) 
Example #23
Source File: default_crypto.py    From plugin.video.netflix with MIT License 5 votes vote down vote up
def decrypt(self, init_vector, ciphertext):
        """Decrypt a ciphertext"""
        cipher = AES.new(self.encryption_key, AES.MODE_CBC, init_vector)
        return Padding.unpad(cipher.decrypt(ciphertext), 16) 
Example #24
Source File: default_crypto.py    From plugin.video.netflix with MIT License 5 votes vote down vote up
def sign(self, message):
        """Sign a message"""
        return base64.standard_b64encode(
            HMAC.new(self.sign_key, message.encode('utf-8'), SHA256).digest()).decode('utf-8') 
Example #25
Source File: default_crypto.py    From plugin.video.netflix with MIT License 5 votes vote down vote up
def _init_keys(self, key_response_data):
        cipher = PKCS1_OAEP.new(self.rsa_key)
        encrypted_encryption_key = base64.standard_b64decode(
            key_response_data['keydata']['encryptionkey'])
        encrypted_sign_key = base64.standard_b64decode(
            key_response_data['keydata']['hmackey'])
        self.encryption_key = _decrypt_key(encrypted_encryption_key, cipher)
        self.sign_key = _decrypt_key(encrypted_sign_key, cipher) 
Example #26
Source File: utils.py    From snapy with MIT License 5 votes vote down vote up
def decrypt(data):
    cipher = AES.new(BLOB_ENCRYPTION_KEY, AES.MODE_ECB)
    return cipher.decrypt(pkcs5_pad(data)) 
Example #27
Source File: utils.py    From snapy with MIT License 5 votes vote down vote up
def decrypt_story(data, key, iv):
    akey = b64decode(key)
    aiv = b64decode(iv)
    cipher = AES.new(akey, AES.MODE_CBC, aiv)
    return cipher.decrypt(pkcs5_pad(data)) 
Example #28
Source File: utils.py    From snapy with MIT License 5 votes vote down vote up
def encrypt(data):
    cipher = AES.new(BLOB_ENCRYPTION_KEY, AES.MODE_ECB)
    return cipher.encrypt(pkcs5_pad(data)) 
Example #29
Source File: jose.py    From jose with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _generate_iv(enc, rng):
    # TODO: This would work only for A128CBC, A192CBC and A256CBC algorithms
    # which are only algorithms supported ATM. In case if new algorithms
    # support added this function should be revised.
    return rng(AES.block_size) 
Example #30
Source File: jose.py    From jose with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def encrypt_oaep(plaintext, jwk):
    return PKCS1_OAEP.new(RSA.importKey(jwk['k'])).encrypt(plaintext)