【问题标题】:Is this a valid byte string for AES Key?这是 AES 密钥的有效字节字符串吗?
【发布时间】:2018-10-01 08:45:15
【问题描述】:

我正在用 Python 3 做一个小项目。

我目前的问题是基于 AES 的文件解密。文件内容(文本)采用 AES 对称加密。

我已经导入 PyCrypto:https://www.dlitz.net/software/pycrypto/api/current/

文档对对称密钥的说明很少:

key (byte string) - 对称密码中使用的密钥。它的长度必须为 16 (AES-128)、24 (AES-192) 或 32 (AES-256) 字节。

我有钥匙,看起来像:

0xB0,0x0D,0xDF,0x9D,...(出于安全原因,我在这里不报告完整的密钥)

无论如何,我的第一个问题:

那是什么字符串?它看起来像 ASCII,但我对编码缺乏深入的了解。我需要任何类型的转换/解码吗?

我写了一个小程序来打开一个文件并解密它。但是 PyCrypto 抛出一个错误,我现在花了 5 个小时反复试验,没有任何进展:

ValueError: AES key must be either 16, 24, or 32 bytes long

所以我都尝试了:

  1. 初始化为字符串:

key = "0xB0,0x0D,0xDF,0x9D,..."

和 2. 作为字节串:

key = b"0xB0,0x0D,0xDF,0x9D,..."

没有效果。

有什么想法或想法吗?

最好的问候, AFX

【问题讨论】:

  • 如果密钥是某种密码或密码短语,则对该密钥进行哈希处理,以便获得随机位。
  • 花五小时学习编码,包括十六进制。

标签: python-3.x encryption utf-8 ascii decoding


【解决方案1】:

你拥有的是一个十六进制字符串。例如,如果你有这个:

0x0F, 0x10, 0x1A

那么这个,浓缩成一个实际的十六进制字符串,就是:

0F101A

作为原始字节,是:

15, 16, 26

您只需先将其转换为字节数组。看看binascii.unhexlify

【讨论】:

    【解决方案2】:

    我想提供适合我的解决方案:

    首先,了解基础知识:

    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
    
    key = 'insert-key-here'
    

    现在,我构建了一个解密方法:

    def decrypt_file(key, in_filename, out_filename=None):
        """ Decrypts a file using AES (CBC mode) with the
            given key.
        """
        backend = default_backend()
        with open(in_filename, mode="r+b") as infile:
            iv = infile.read(16) #Calling .read() will move the iterator exactly as many positions
            cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
            decryptor = cipher.decryptor()
            with open(out_filename, mode="w+b") as outfile:
                cipher_text = infile.read() #Only the first 16byte are the iv, the rest is the cipher-text
                outfile.write(decryptor.update(cipher_text) + decryptor.finalize())
    

    这是关键:我必须先将密钥转换为字节串

    #Transform key to byte-string
    key_int = [int(x,0) for x in key.split(',')]
    decrypt_byte_key = b''
    for x in key_int:
        decrypt_byte_key += x.to_bytes(1, 'little')
    

    最后,你可以在你的文件上运行它:

    decrypt_file(decrypt_byte_key, "input.enc", "output.txt")
    

    玩得开心。

    【讨论】:

      猜你喜欢
      • 2015-03-18
      • 1970-01-01
      • 1970-01-01
      • 2019-09-30
      • 2021-04-12
      • 1970-01-01
      • 1970-01-01
      • 2017-04-26
      • 1970-01-01
      相关资源
      最近更新 更多