AES-如何将字节字符串转换为字节字节字符串?

时间:2019-10-29 23:57:18

标签: python encryption cryptography aes

我正在尝试AES。我正在尝试完全在过程中传递加密的消息:

    import hashlib
    import os
    import base64

    from Crypto.Cipher import AES

    IV_SIZE = 16    # 128 bit, fixed for the AES algorithm
    KEY_SIZE = 32   # 256 bit meaning AES-256, can also be 128 or 192 bits
    SALT_SIZE = 16  # This size is arbitrary

    cleartext = b'Lorem ipsum'
    password = b'highly secure encryption password'
    salt = os.urandom(SALT_SIZE)
    derived = hashlib.pbkdf2_hmac('sha256', password, salt, 100000,
                              dklen=IV_SIZE + KEY_SIZE)
    iv = derived[0:IV_SIZE]
    key = derived[IV_SIZE:]

    encrypted = salt + AES.new(key, AES.MODE_CFB, iv).encrypt(cleartext)

    print(encrypted)
    ############################################
    #This is where the examples are being tried
    encrypted = str(encrypted).encode('unicode-escape')
    ###########################################

    encryptedString = base64.encodebytes(encrypted)

    print(encryptedString) 

    encrypted = base64.decodebytes(encryptedString) # <- get the bytes back

    salt = encrypted[0:SALT_SIZE]
    derived = hashlib.pbkdf2_hmac('sha256', password, salt, 100000,
                              dklen=IV_SIZE + KEY_SIZE)
    iv = derived[0:IV_SIZE]
    key = derived[IV_SIZE:]
    cleartext = AES.new(key, AES.MODE_CFB, iv).decrypt(encrypted[SALT_SIZE:])

    print(cleartext)

我收到以下错误:预期的类似字节的对象,而不是str

基本上,我正在尝试将字符串(字节字符串)转换为字节(字节字符串)。通常,我会在字符串前面加上b,例如: b'?j \ xf5 \ xd3 \ x8bP \ xe5 \ xd5 \ xcd \ xa2] \ xa7 \ xf7 \ xc7 \ x9cO \ x92 \ x0f \ xdb} \ xf5N \ xb94J \ xc7 \ x13'

但是在这种情况下,加密的消息将作为字符串接收,并且必须转换为字节。

我尝试过:

encrypted = str(已加密).encode('utf-8')

已加密=字节(str(已加密),'utf-8')

encrypted = str(encrypted).encode('unicode-escape')

这些示例不会产生错误,但是脚本会再次对其加密而不是解密。

1 个答案:

答案 0 :(得分:0)

使用snakecharmerb的建议答案:

wordCount