通过Python解密AES字符串时出现非Unicode字符?

时间:2019-07-06 21:03:08

标签: python encryption aes

我正在进行CTF挑战,要求我解密密文字符串。我得到了用于加密字符串的Python脚本,它还包括一个解密功能。​​

我已经将代码合并到自己的脚本中,该脚本采用密文和密钥选项,并且应该输出纯文本密码。但是,我找回乱码,我不确定为什么。

加密功能:

def encrypt(plaintext, key):
    """
    Encrypt the plaintext with AES method.

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

    iv = os.urandom(iv_size)
    cipher = Cipher(AES(pad(key)), CFB8(iv), default_backend())
    encryptor = cipher.encryptor()

    # If user has entered non ascii password (Python2)
    # we have to encode it first
    if isinstance(plaintext, six.text_type):
        plaintext = plaintext.encode()

    return base64.b64encode(iv + encryptor.update(plaintext) +
                            encryptor.finalize())

我的代码:

#!/usr/bin/env python
from __future__ import division
import sys
import os
import hashlib
import base64
import six
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import Cipher
from cryptography.hazmat.primitives.ciphers.algorithms import AES
from cryptography.hazmat.primitives.ciphers.modes import CFB8

padding_string = b'}'
iv_size = AES.block_size // 8
ciphertext = sys.argv[1]
key = sys.argv[2]

def decrypt(ciphertext, key):
    """
    Decrypt the AES encrypted string.

    Parameters:
        ciphertext -- Encrypted string with AES method.
        key        -- key to decrypt the encrypted string.
    """
    # ciphertext = unicode(ciphertext)
    print 'Initial crypt text: ' + ciphertext
    ciphertext = base64.b64decode(ciphertext)
    print 'After base64: ' + ciphertext
    iv = ciphertext[:iv_size]
    print 'After IV call: ' + iv
    print '--------------------------'
    cipher = Cipher(AES(pad(key)), CFB8(iv), default_backend())
    decryptor = cipher.decryptor()
    decrypted_hash = decryptor.update(ciphertext[iv_size:]) + decryptor.finalize()
    print decrypted_hash
    return decrypted_hash

def pad(key):
    """Add padding to the key."""

    if isinstance(key, six.text_type):
        key = key.encode()

    # Key must be maximum 32 bytes long, so take first 32 bytes
    key = key[:32]

    # If key size is 16, 24 or 32 bytes then padding is not required
    if len(key) in (16, 24, 32):
        return key

    # Add padding to make key 32 bytes long
    return key.ljust(32, padding_string)

if __name__ == '__main__':
    hash1 = decrypt(ciphertext, key)
    # final_hash = unicode(hash1, errors='replace')
    print 'Final Hash is: ' + hash1

正如从print语句中可以看到的那样,我已经调试到了最初的base64调用。即使在最初的base64调用之后,它仍然会打印出乱码。

给定的变量是:

密文:utUU0jkamCZDmqFLOrAuPjFxL0zp8zWzISe5MF0GY/l8Silrmu3caqrtjaVjLQlvFFEgESGz

键:R_EFY1hb236guS3jNq1aHyPcruXbjk7Ff-QwL6PMqJM=

我在这里想念东西吗?

0 个答案:

没有答案