Python源码示例:Crypto.Cipher.AES.MODE_CFB

示例1
def test_aes_128_cfb128(self):
        plaintext =     '6bc1bee22e409f96e93d7e117393172a' +\
                        'ae2d8a571e03ac9c9eb76fac45af8e51' +\
                        '30c81c46a35ce411e5fbc1191a0a52ef' +\
                        'f69f2445df4f9b17ad2b417be66c3710'
        ciphertext =    '3b3fd92eb72dad20333449f8e83cfb4a' +\
                        'c8a64537a0b3a93fcde3cdad9f1ce58b' +\
                        '26751f67a3cbb140b1808cf187a4f4df' +\
                        'c04b05357c5d1c0eeac4c66f9ff7f2e6'
        key =           '2b7e151628aed2a6abf7158809cf4f3c'
        iv =            '000102030405060708090a0b0c0d0e0f'

        key = unhexlify(key)
        iv = unhexlify(iv)
        plaintext = unhexlify(plaintext)
        ciphertext = unhexlify(ciphertext)

        cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=128)
        self.assertEqual(cipher.encrypt(plaintext), ciphertext)
        cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=128)
        self.assertEqual(cipher.decrypt(ciphertext), plaintext) 
示例2
def decrypt_private_key(encrypted_private_key: bytes, password: str) -> str:
        '''
        Decrypt private key with the password.

        Args:
            encrypted_private_key (bytes): encrypted private key
            password (str): password to decrypt private key with

        Returns:
            str: decrypted private key
        '''
        encrypted_private_key = base64.b64decode(encrypted_private_key)
        iv = encrypted_private_key[:AES.block_size]
        cipher = AES.new(sha256(bytes(password.encode('utf-8'))).digest(), AES.MODE_CFB, iv)
        private_key = cipher.decrypt(encrypted_private_key[AES.block_size:])
        return str(private_key, 'ascii') 
示例3
def encrypt(plaintext, key):
    """
    Encrypt the plaintext with AES method.

    Parameters:
        plaintext -- String to be encrypted.
        key       -- Key for encryption.
    """

    iv = Random.new().read(AES.block_size)
    cipher = AES.new(pad(key), AES.MODE_CFB, iv)
    # If user has entered non ascii password (Python2)
    # we have to encode it first
    if hasattr(str, 'decode'):
        plaintext = plaintext.encode('utf-8')
    encrypted = base64.b64encode(iv + cipher.encrypt(plaintext))

    return encrypted 
示例4
def decrypt(ciphertext, key):
    """
    Decrypt the AES encrypted string.

    Parameters:
        ciphertext -- Encrypted string with AES method.
        key        -- key to decrypt the encrypted string.
    """

    global padding_string

    ciphertext = base64.b64decode(ciphertext)
    iv = ciphertext[:AES.block_size]
    cipher = AES.new(pad(key), AES.MODE_CFB, iv)
    decrypted = cipher.decrypt(ciphertext[AES.block_size:])

    return decrypted 
示例5
def encryptData(self, encryptKey, privParameters, dataToEncrypt):
        if AES is None:
            raise error.StatusInformation(
                errorIndication=errind.encryptionError
                )
 
        snmpEngineBoots, snmpEngineTime, salt = privParameters

        # 3.3.1.1
        aesKey, iv, salt = self.__getEncryptionKey(
            encryptKey, snmpEngineBoots, snmpEngineTime
            )

        # 3.3.1.3
        aesObj = AES.new(aesKey, AES.MODE_CFB, iv, segment_size=128)

        # PyCrypto seems to require padding
        dataToEncrypt = dataToEncrypt + univ.OctetString((0,) * (16-len(dataToEncrypt)%16)).asOctets()

        ciphertext = aesObj.encrypt(dataToEncrypt)

        # 3.3.1.4
        return univ.OctetString(ciphertext), univ.OctetString(salt)
        
    # 3.2.4.2 
示例6
def decrypt_session_key(db,kdfDeriveS,aes):
    masterKey=b''
    conn=ctx.sqlite_run_cmd(db,"select k,v from secconfig;")
    if (conn==-1):
        return masterKey
    rows=ctx.sqlite_get_data_size(conn)[0]
    encnames=['RSA_PRIV','HID','PRIVATE_KEY','MASTER_KEY','ECC_PRIV','ENC_TEST_KEY','DURESS_PWD','SERVER_SES_KEY']
    debase=['SERV_PUB_KEY','PUBLIC_KEY','ECC_PUB','ECDH_SERVPUB','AGENT_PIN']
    for i in range(0,rows):
        name=ctx.sqlite_get_data(conn,i,0)
        if (name in encnames):
                IV = b'0' * 16
                aes = AES.new(kdfDeriveS[0:32], AES.MODE_CFB, IV, segment_size=128)
                data = aes.decrypt(base64.b64decode(ctx.sqlite_get_data(conn,i,1)))
                if (name == 'MASTER_KEY'):
                    masterKey=data
        elif (name in debase):
            data=base64.b64decode(ctx.sqlite_get_data(conn,i,1))
    ctx.sqlite_cmd_close(conn)
    return masterKey 
示例7
def test_aes_128_cfb128(self):
        plaintext =     '6bc1bee22e409f96e93d7e117393172a' +\
                        'ae2d8a571e03ac9c9eb76fac45af8e51' +\
                        '30c81c46a35ce411e5fbc1191a0a52ef' +\
                        'f69f2445df4f9b17ad2b417be66c3710'
        ciphertext =    '3b3fd92eb72dad20333449f8e83cfb4a' +\
                        'c8a64537a0b3a93fcde3cdad9f1ce58b' +\
                        '26751f67a3cbb140b1808cf187a4f4df' +\
                        'c04b05357c5d1c0eeac4c66f9ff7f2e6'
        key =           '2b7e151628aed2a6abf7158809cf4f3c'
        iv =            '000102030405060708090a0b0c0d0e0f'

        key = unhexlify(key)
        iv = unhexlify(iv)
        plaintext = unhexlify(plaintext)
        ciphertext = unhexlify(ciphertext)

        cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=128)
        self.assertEqual(cipher.encrypt(plaintext), ciphertext)
        cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=128)
        self.assertEqual(cipher.decrypt(ciphertext), plaintext) 
示例8
def test_aes_256_cfb128(self):
        plaintext =     '6bc1bee22e409f96e93d7e117393172a' +\
                        'ae2d8a571e03ac9c9eb76fac45af8e51' +\
                        '30c81c46a35ce411e5fbc1191a0a52ef' +\
                        'f69f2445df4f9b17ad2b417be66c3710'

        ciphertext =    'dc7e84bfda79164b7ecd8486985d3860' +\
                        '39ffed143b28b1c832113c6331e5407b' +\
                        'df10132415e54b92a13ed0a8267ae2f9' +\
                        '75a385741ab9cef82031623d55b1e471'
        key =           '603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4'
        iv =            '000102030405060708090a0b0c0d0e0f'

        key = unhexlify(key)
        iv = unhexlify(iv)
        plaintext = unhexlify(plaintext)
        ciphertext = unhexlify(ciphertext)

        cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=128)
        self.assertEqual(cipher.encrypt(plaintext), ciphertext)
        cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=128)
        self.assertEqual(cipher.decrypt(ciphertext), plaintext) 
示例9
def test_aes_256_cfb128(self):
        plaintext =     '6bc1bee22e409f96e93d7e117393172a' +\
                        'ae2d8a571e03ac9c9eb76fac45af8e51' +\
                        '30c81c46a35ce411e5fbc1191a0a52ef' +\
                        'f69f2445df4f9b17ad2b417be66c3710'

        ciphertext =    'dc7e84bfda79164b7ecd8486985d3860' +\
                        '39ffed143b28b1c832113c6331e5407b' +\
                        'df10132415e54b92a13ed0a8267ae2f9' +\
                        '75a385741ab9cef82031623d55b1e471'
        key =           '603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4'
        iv =            '000102030405060708090a0b0c0d0e0f'

        key = unhexlify(key)
        iv = unhexlify(iv)
        plaintext = unhexlify(plaintext)
        ciphertext = unhexlify(ciphertext)

        cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=128)
        self.assertEqual(cipher.encrypt(plaintext), ciphertext)
        cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=128)
        self.assertEqual(cipher.decrypt(ciphertext), plaintext) 
示例10
def get_cipher(self, key, iv):
            if len(key) > 32:
                raise ValueError('Key length cannot exceed 32 bytes.')
            key = key + ' ' * (32 - len(key))
            return AES.new(key, AES.MODE_CFB, iv) 
示例11
def init_crypto_nt6(self):
        self.iv = self.get_constant_object(
            'InitializationVector', 'String', length=16, term=None).v()

        aes_handle = self.get_constant_object(
            'hAesKey', target='Pointer',
            target_args=dict(target='_KIWI_BCRYPT_HANDLE_KEY'))

        self.aes_key = aes_handle.key.hardkey.data.v()

        des_handle = self.get_constant_object(
            'h3DesKey', target='Pointer',
            target_args=dict(target='_KIWI_BCRYPT_HANDLE_KEY'))

        self.des_key = des_handle.key.hardkey.data.v()

        try:
            cipher = AES.new(self.aes_key, AES.MODE_CFB, self.iv)
            cipher = DES3.new(self.des_key, DES3.MODE_CBC, self.iv[:8])
            cipher = None
            decryption_enabled = True
        except ValueError as e_ve:
            decryption_enabled = False
            logging.warning('init_crypto_nt6 exception {}'.format(e_ve))
        finally:
            return decryption_enabled 
示例12
def decrypt_nt6(self, encrypted):
        if not self.decryption_enabled:
            return obj.NoneObject()

        cipher = None
        if self.iv:
            if len(encrypted) % 8:
                cipher = AES.new(self.aes_key, AES.MODE_CFB, self.iv)
            else:
                if self.des_key:
                    cipher = DES3.new(self.des_key, DES3.MODE_CBC, self.iv[:8])
        if cipher and encrypted:
            return cipher.decrypt(encrypted)
        return obj.NoneObject() 
示例13
def ComputeNetlogonCredentialAES(inputData, Sk):
    IV='\x00'*16
    Crypt1 = AES.new(Sk, AES.MODE_CFB, IV)
    return Crypt1.encrypt(inputData)

# Section 3.1.4.3.1 
示例14
def encryptSequenceNumberAES(sequenceNum, checkSum, sessionKey):
    # [MS-NRPC] Section 3.3.4.2.1, point 9
    IV = checkSum[:8] + checkSum[:8]
    Cipher = AES.new(sessionKey, AES.MODE_CFB, IV)
    return Cipher.encrypt(sequenceNum) 
示例15
def decryptSequenceNumberAES(sequenceNum, checkSum, sessionKey):
    # [MS-NRPC] Section 3.3.4.2.1, point 9
    IV = checkSum[:8] + checkSum[:8]
    Cipher = AES.new(sessionKey, AES.MODE_CFB, IV)
    return Cipher.decrypt(sequenceNum) 
示例16
def SEAL(data, confounder, sequenceNum, key, aes = False):
    signature = SIGN(data, confounder, sequenceNum, key, aes)
    sequenceNum = deriveSequenceNumber(sequenceNum)
    XorKey = []
    for i in key:
       XorKey.append(chr(ord(i) ^ 0xf0))

    XorKey = ''.join(XorKey)
    if aes is False:
        hm = hmac.new(XorKey)
        hm.update('\x00'*4)
        hm2 = hmac.new(hm.digest())
        hm2.update(sequenceNum)
        encryptionKey = hm2.digest()

        cipher = ARC4.new(encryptionKey)
        cfounder = cipher.encrypt(confounder)
        cipher = ARC4.new(encryptionKey)
        encrypted = cipher.encrypt(data)

        signature['Confounder'] = cfounder

        return encrypted, signature
    else:
        IV = sequenceNum + sequenceNum
        cipher = AES.new(XorKey, AES.MODE_CFB, IV)
        cfounder = cipher.encrypt(confounder)
        encrypted = cipher.encrypt(data)

        signature['Confounder'] = cfounder

        return encrypted, signature 
示例17
def UNSEAL(data, auth_data, key, aes = False):
    auth_data = NL_AUTH_SIGNATURE(auth_data)
    XorKey = []
    for i in key:
       XorKey.append(chr(ord(i) ^ 0xf0))

    XorKey = ''.join(XorKey)
    if aes is False:
        sequenceNum = decryptSequenceNumberRC4(auth_data['SequenceNumber'], auth_data['Checksum'],  key)
        hm = hmac.new(XorKey)
        hm.update('\x00'*4)
        hm2 = hmac.new(hm.digest())
        hm2.update(sequenceNum)
        encryptionKey = hm2.digest()

        cipher = ARC4.new(encryptionKey)
        cfounder = cipher.encrypt(auth_data['Confounder'])
        cipher = ARC4.new(encryptionKey)
        plain = cipher.encrypt(data)

        return plain, cfounder
    else:
        sequenceNum = decryptSequenceNumberAES(auth_data['SequenceNumber'], auth_data['Checksum'],  key)
        IV = sequenceNum + sequenceNum
        cipher = AES.new(XorKey, AES.MODE_CFB, IV)
        cfounder = cipher.decrypt(auth_data['Confounder'])
        plain = cipher.decrypt(data)
        return plain, cfounder 
示例18
def generated_cipher(shared_secret):
    """Creates a AES128 stream cipher using cfb8 mode"""
    return AES.new(shared_secret, AES.MODE_CFB, shared_secret) 
示例19
def encrypt_private_key(private_key: str, password: str) -> bytes:
        '''
        Encrypt private key with the password.

        Args:
            private_key (str): private key
            password (str): password to encrypt private key with

        Returns:
            bytes: encrpyted private key
        '''
        iv = Random.new().read(AES.block_size)
        cipher = AES.new(sha256(bytes(password.encode('utf-8'))).digest(), AES.MODE_CFB, iv)
        encrypted_private_key = base64.b64encode(iv + cipher.encrypt(bytes(private_key.encode('utf-8'))))
        return encrypted_private_key 
示例20
def _create_cipher(self, password, salt, IV):
        """
        Create the cipher object to encrypt or decrypt a payload.
        """
        from Crypto.Protocol.KDF import PBKDF2
        from Crypto.Cipher import AES

        pw = PBKDF2(password, salt, dkLen=self.block_size)
        return AES.new(pw[: self.block_size], AES.MODE_CFB, IV) 
示例21
def ComputeNetlogonCredentialAES(inputData, Sk):
    IV='\x00'*16
    Crypt1 = AES.new(Sk, AES.MODE_CFB, IV)
    return Crypt1.encrypt(inputData)

# Section 3.1.4.3.1 
示例22
def encryptSequenceNumberAES(sequenceNum, checkSum, sessionKey):
    # [MS-NRPC] Section 3.3.4.2.1, point 9
    IV = checkSum[:8] + checkSum[:8]
    Cipher = AES.new(sessionKey, AES.MODE_CFB, IV)
    return Cipher.encrypt(sequenceNum) 
示例23
def decryptSequenceNumberAES(sequenceNum, checkSum, sessionKey):
    # [MS-NRPC] Section 3.3.4.2.1, point 9
    IV = checkSum[:8] + checkSum[:8]
    Cipher = AES.new(sessionKey, AES.MODE_CFB, IV)
    return Cipher.decrypt(sequenceNum) 
示例24
def SEAL(data, confounder, sequenceNum, key, aes = False):
    signature = SIGN(data, confounder, sequenceNum, key, aes)
    sequenceNum = deriveSequenceNumber(sequenceNum)
    XorKey = []
    for i in key:
       XorKey.append(chr(ord(i) ^ 0xf0))

    XorKey = ''.join(XorKey)
    if aes is False:
        hm = hmac.new(XorKey)
        hm.update('\x00'*4)
        hm2 = hmac.new(hm.digest())
        hm2.update(sequenceNum)
        encryptionKey = hm2.digest()

        cipher = ARC4.new(encryptionKey)
        cfounder = cipher.encrypt(confounder)
        cipher = ARC4.new(encryptionKey)
        encrypted = cipher.encrypt(data)

        signature['Confounder'] = cfounder

        return encrypted, signature
    else:
        IV = sequenceNum + sequenceNum
        cipher = AES.new(XorKey, AES.MODE_CFB, IV)
        cfounder = cipher.encrypt(confounder)
        encrypted = cipher.encrypt(data)

        signature['Confounder'] = cfounder

        return encrypted, signature 
示例25
def UNSEAL(data, auth_data, key, aes = False):
    auth_data = NL_AUTH_SIGNATURE(auth_data)
    XorKey = []
    for i in key:
       XorKey.append(chr(ord(i) ^ 0xf0))

    XorKey = ''.join(XorKey)
    if aes is False:
        sequenceNum = decryptSequenceNumberRC4(auth_data['SequenceNumber'], auth_data['Checksum'],  key)
        hm = hmac.new(XorKey)
        hm.update('\x00'*4)
        hm2 = hmac.new(hm.digest())
        hm2.update(sequenceNum)
        encryptionKey = hm2.digest()

        cipher = ARC4.new(encryptionKey)
        cfounder = cipher.encrypt(auth_data['Confounder'])
        cipher = ARC4.new(encryptionKey)
        plain = cipher.encrypt(data)

        return plain, cfounder
    else:
        sequenceNum = decryptSequenceNumberAES(auth_data['SequenceNumber'], auth_data['Checksum'],  key)
        IV = sequenceNum + sequenceNum
        cipher = AES.new(XorKey, AES.MODE_CFB, IV)
        cfounder = cipher.decrypt(auth_data['Confounder'])
        plain = cipher.decrypt(data)
        return plain, cfounder 
示例26
def __decrypt_pyc(self, extracted_binary_path, encryption_key):
        # Code reference from https://0xec.blogspot.sg/2017/02/extracting-encrypted-pyinstaller.html
        from Crypto.Cipher import AES
        import zlib
        crypt_block_size = 16
        encrypted_pyc_folder = os.path.join(extracted_binary_path, "out00-PYZ.pyz_extracted")
        encrypted_pyc_list = os.listdir(encrypted_pyc_folder)
        for x, file_name in enumerate(encrypted_pyc_list):
            # File that is decrypted will end with pyc and file with py extension will not be bothered as well
            if ".pyc.encrypted.pyc" not in file_name and ".pyc.encrypted.py" not in file_name and ".pyc.encrypted" in file_name:
                try:
                    encrypted_pyc = os.path.join(encrypted_pyc_folder, file_name)
                    encrypted_pyc_file = open(encrypted_pyc, 'rb')
                    decrypted_pyc_file = open(encrypted_pyc + ".pyc", 'wb')
                    initialization_vector = encrypted_pyc_file.read(crypt_block_size)
                    cipher = AES.new(encryption_key.encode(), AES.MODE_CFB, initialization_vector)
                    plaintext = zlib.decompress(cipher.decrypt(encrypted_pyc_file.read()))
                    decrypted_pyc_file.write(b'\x03\xf3\x0d\x0a\0\0\0\0')
                    decrypted_pyc_file.write(plaintext)
                    encrypted_pyc_file.close()
                    decrypted_pyc_file.close()
                except Exception as e:
                    print("[-] Exception occured during pyc decryption and decompiling")
                    print("[-] Error message: {0}".format(e.message))
                    sys.exit(1)
        
        try:
            PythonExectable.decompile_pyc(encrypted_pyc_folder, PythonExectable.current_dir_pyc_files(encrypted_pyc_folder))
        finally:
            for x, file_name in enumerate(PythonExectable.current_dir_pyc_files(encrypted_pyc_folder)):
                full_path = os.path.join(encrypted_pyc_folder, file_name)
                if os.path.exists(full_path):
                    os.remove(full_path)


    # To deal with encrypted pyinstaller binary if it's encrypted 
示例27
def aes_encrypt(skey, m):
    '''
    Encrypt given message with shared key.
    '''
    iv = '\x00' * 16
    stream = AES.new(skey, AES.MODE_CFB, iv)
    return stream.encrypt(m) 
示例28
def aes_decrypt(skey, c):
    '''
    Decrypt given message with shared key.
    '''
    iv = '\x00' * 16
    stream=AES.new(skey, AES.MODE_CFB, iv)
    return stream.decrypt(c) 
示例29
def AES_encrypt(data, key):
        aes = AES.new(key, AES.MODE_CFB)
        return aes.encrypt(data) 
示例30
def AES_decrypt(data, key):
        aes = AES.new(key, AES.MODE_CFB)
        return aes.decrypt(data)