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: 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 #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: 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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
Source File: test_encryption.py    From tbk with GNU General Public License v3.0 5 votes vote down vote up
def test_get_decrypted_message(self):
        recipient_key_bytes = int(self.recipient_key.publickey().n.bit_length() / 8)
        decryption = Decryption(self.recipient_key, self.sender_key)
        iv = Random.new().read(16)
        key = Random.new().read(32)
        encrypted_key = Random.new().read(recipient_key_bytes)
        message = ("a" * 2000).encode('utf-8')
        block_size = AES.block_size
        pad = lambda s: s + (block_size - len(s) % block_size) * chr(block_size - len(s) % block_size).encode('utf-8')
        message_to_encrypt = pad(message)
        cipher = AES.new(key, mode=AES.MODE_CBC, IV=iv)
        encrypted_message = cipher.encrypt(message_to_encrypt)

        self.assertEqual(message,
                         decryption.get_decrypted_message(iv, key, iv + encrypted_key + encrypted_message)) 
Example #13
Source File: crypto.py    From Apfell with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def hash_MD5(data) -> str:
    if isinstance(data, str):
        hash_digest = MD5.new(data=str.encode(data))
    else:
        hash_digest = MD5.new(data=data)
    return hash_digest.hexdigest()


# https://pycryptodome.readthedocs.io/en/latest/src/examples.html 
Example #14
Source File: test_encryption.py    From tbk with GNU General Public License v3.0 5 votes vote down vote up
def test_get_signature(self):
        sender_key_bytes = int(self.sender_key.publickey().n.bit_length() / 8)
        decryption = Decryption(self.recipient_key, self.sender_key)

        signature = Random.new().read(sender_key_bytes)
        message = Random.new().read(500)
        decrypted_message = signature + message

        self.assertEqual(signature, decryption.get_signature(decrypted_message)) 
Example #15
Source File: test_encryption.py    From tbk with GNU General Public License v3.0 5 votes vote down vote up
def test_get_message(self):
        sender_key_bytes = int(self.sender_key.publickey().n.bit_length() / 8)
        decryption = Decryption(self.recipient_key, self.sender_key)

        signature = Random.new().read(sender_key_bytes)
        message = Random.new().read(500)
        decrypted_message = signature + message

        self.assertEqual(message, decryption.get_message(decrypted_message)) 
Example #16
Source File: crypto.py    From Apfell with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def decrypt_AES256(data: bytes, key: bytes):
    # hmac should include IV
    mac = data[-32:]  # sha256 hmac at the end
    iv = data[:16]  # 16 Bytes for IV at the beginning
    message = data[16:-32]  # the rest is the message
    h = HMAC.new(key=key, msg=iv + message, digestmod=SHA256)
    h.verify(mac)
    decryption_cipher = AES.new(key, AES.MODE_CBC, iv=iv)
    decrypted_message = decryption_cipher.decrypt(message)
    # print(decrypted_message)
    # now to remove any padding that was added on to make it the right block size of 16
    return unpad(decrypted_message, 16) 
Example #17
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 #18
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 #19
Source File: privrules.py    From Loki with GNU General Public License v3.0 5 votes vote down vote up
def generate_RSA_key(keysize):
    random_generator = Random.new().read
    key = RSA.generate(keysize, random_generator)
    return key 
Example #20
Source File: encryption.py    From tbk with GNU General Public License v3.0 5 votes vote down vote up
def get_iv(self):
        return Random.new().read(16) 
Example #21
Source File: test_encryption.py    From tbk with GNU General Public License v3.0 5 votes vote down vote up
def test_get_key(self):
        decryption = Decryption(self.recipient_key, self.sender_key)
        raw = Random.new().read(16)
        key = Random.new().read(32)
        cipher = PKCS1_OAEP.new(self.recipient_key.publickey())
        encrypted_key = cipher.encrypt(key)
        raw += encrypted_key + Random.new().read(2000)

        self.assertEqual(key, decryption.get_key(raw)) 
Example #22
Source File: test_encryption.py    From tbk with GNU General Public License v3.0 5 votes vote down vote up
def test_decrypt_incorrect_length(self, verify, get_message, get_signature, get_decrypted_message, get_key, get_iv):
        decryption = Decryption(self.recipient_key, self.sender_key)
        get_key.side_effect = DecryptionError("Incorrect message length.")
        raw = Random.new().read(2000)
        encrypted = base64.b64encode(raw)
        verify.return_value = False

        six.assertRaisesRegex(self, DecryptionError, "Incorrect message length.",
                                decryption.decrypt, encrypted) 
Example #23
Source File: test_encryption.py    From tbk with GNU General Public License v3.0 5 votes vote down vote up
def test_decrypt_invalid(self, verify, get_message, get_signature, get_decrypted_message, get_key, get_iv):
        decryption = Decryption(self.recipient_key, self.sender_key)
        raw = Random.new().read(2000)
        encrypted = base64.b64encode(raw)
        verify.return_value = False

        six.assertRaisesRegex(self, InvalidMessageException, "Invalid message signature",
                                decryption.decrypt, encrypted) 
Example #24
Source File: test_encryption.py    From tbk with GNU General Public License v3.0 5 votes vote down vote up
def test_encrypt_message(self):
        encryption = Encryption(self.sender_key, self.recipient_key)
        key = encryption.get_key()
        iv = encryption.get_iv()
        message = Random.new().read(10)
        signed_message = encryption.sign_message(message)

        encrypted = encryption.encrypt_message(signed_message, message, key, iv)

        cipher = AES.new(key, AES.MODE_CBC, iv)
        unpad = lambda s: s[:-ord(s[len(s) - 1:])]
        decrypted = unpad(cipher.decrypt(encrypted))

        self.assertEqual(decrypted, signed_message + message) 
Example #25
Source File: test_encryption.py    From tbk with GNU General Public License v3.0 5 votes vote down vote up
def test_sign_message(self):
        message = Random.new().read(2000)
        encryption = Encryption(self.sender_key, self.recipient_key)

        signed_message = encryption.sign_message(message)

        public_key = self.sender_key.publickey()
        hash = SHA512.new(message)
        verifier = PKCS1_v1_5.new(public_key)
        self.assertTrue(verifier.verify(hash, signed_message)) 
Example #26
Source File: test_encryption.py    From tbk with GNU General Public License v3.0 5 votes vote down vote up
def test_get_key(self, Random):
        expected = Random.new.return_value.read.return_value
        encryption = Encryption(self.sender_key, self.recipient_key)

        self.assertEqual(encryption.get_key(), expected)
        Random.new.return_value.read.assert_called_once_with(32) 
Example #27
Source File: test_encryption.py    From tbk with GNU General Public License v3.0 5 votes vote down vote up
def test_get_iv(self, Random):
        expected = Random.new.return_value.read.return_value
        encryption = Encryption(self.sender_key, self.recipient_key)

        self.assertEqual(encryption.get_iv(), expected)
        Random.new.return_value.read.assert_called_once_with(16) 
Example #28
Source File: encryption.py    From tbk with GNU General Public License v3.0 5 votes vote down vote up
def verify(self, signature, message):
        hash = SHA512.new(message)
        verifier = PKCS1_v1_5.new(self.sender_key)

        return verifier.verify(hash, signature) 
Example #29
Source File: encryption.py    From tbk with GNU General Public License v3.0 5 votes vote down vote up
def get_decrypted_message(self, iv, key, raw):
        recipient_key_bytes = int(self.recipient_key.publickey().n.bit_length() / 8)
        encrypted_message = raw[16 + recipient_key_bytes:]
        unpad = lambda s: s[:-ord(s[len(s) - 1:])]
        cipher = AES.new(key, AES.MODE_CBC, iv)
        return unpad(cipher.decrypt(encrypted_message)) 
Example #30
Source File: encryption.py    From tbk with GNU General Public License v3.0 5 votes vote down vote up
def sign_message(self, message):
        hash = SHA512.new(message)
        signer = PKCS1_v1_5.new(self.sender_key)
        return signer.sign(hash)