【问题标题】:Input strings must be a multiple of 16 in length Python pycrypto输入字符串的长度必须是 16 的倍数 Python pycrypto
【发布时间】:2019-01-04 01:24:48
【问题描述】:

我正在尝试使用 python 进行密码学并有一个问题。这是我为学习和测试所做的一些代码。

#!/usr/bin/python3
import getpass
from Crypto.Cipher import AES
import hashlib
import random
import sys
import os

the_input = getpass.getpass("Enter password: ")
theHash = hashlib.sha256(the_input.encode("utf-8")).hexdigest()

key = theHash[0:16]
#IV = ''.join([chr(random.randint(0, 0xff)) for i in range(16)])
IV = os.urandom(16)
print("THEHASH: ", key, "Leangth: ", len(key))
print( "IVlen: ", len(IV), "|SYS,GETSIZEOF: ", sys.getsizeof(IV))
print("This is the IV: ", IV)
def Encrypt_str():
    aes1 = AES.new(key, AES.MODE_CBC, IV)
    data = 'whatevertest'.zfill(16)

    encr = aes1.encrypt(data)
    print("The ENCRYPTION: ",encr)
    aes2 = AES.new(key, AES.MODE_CBC, IV)
    decr = aes2.decrypt(encr)
    print("Decrypted: ", decr)

def Decrypt_str():
    aes2 = AES.new(key, AES.MODE_CBC, IV)
    inpa1 = input("Enter cip:")
    decr = aes2.decrypt(inpa1)
    print(decr)

Encrypt_str()
Decrypt_str()

上线

print("The ENCRYPTION: ",encr)

它使用 .zfill(16) 字节打印加密代码

那个代码是 b'\x0c\x97\x8e\x1b\xa9\x10a\n\x07\xde\x16\xa3\xf7\x10\x9f5'

当我跑步时

len('\x0c\x97\x8e\x1b\xa9\x10a\n\x07\xde\x16\xa3\xf7\x10\x9f5') in interpreter

我得到 16 作为回报,当我将加密的 aes 代码粘贴到

inpa1 = input("Enter cip:")

我来了

File "newtest.py", line 35, in <module>
    Decrypt_str()
  File "newtest.py", line 31, in Decrypt_str
    decr = aes2.decrypt(inpa1)
  File "/usr/lib/python3/dist-packages/Crypto/Cipher/blockalgo.py", line 295, i$
    return self._cipher.decrypt(ciphertext)
ValueError: Input strings must be a multiple of 16 in length

但我仍然可以在同一函数中解密相同的 16 个字节

decr = aes2.decrypt(encr)

我觉得很奇怪......所以我真的不知道这是如何工作的。会得到一些帮助。

【问题讨论】:

  • input() 不会将这些反斜杠转义码转换为字节。使用 base-64 编码之类的。

标签: python python-3.x aes pycrypto


【解决方案1】:

如果您将\x0c\x97\x8e\x1b\xa9\x10a\n\x07\xde\x16\xa3\xf7\x10\x9f5 直接粘贴到输入提示符中,则反斜杠将被转义。

>>> example=input("Prompt: ")
Prompt: \x0c\x97\x8e\x1b\xa9\x10a\n\x07\xde\x16\xa3\xf7\x10\x9f5
>>> example
'\\x0c\\x97\\x8e\\x1b\\xa9\\x10a\\n\\x07\\xde\\x16\\xa3\\xf7\\x10\\x9f5'
>>> print(example)
\x0c\x97\x8e\x1b\xa9\x10a\n\x07\xde\x16\xa3\xf7\x10\x9f5

通常在传递加密值时,最好对值进行 base64 编码。然后在解密值之前对值进行解码。

>>> import base64
>>> enc=b'\x0c\x97\x8e\x1b\xa9\x10a\n\x07\xde\x16\xa3\xf7\x10\x9f5'
>>> base64_enc = base64.b64encode(enc)
>>> print(base64_enc)
b'DJeOG6kQYQoH3haj9xCfNQ=='
>>>
>>> i=input("Prompt: ")
Prompt: DJeOG6kQYQoH3haj9xCfNQ==
>>>
>>> i
'DJeOG6kQYQoH3haj9xCfNQ=='
>>> denc=base64.b64decode(i)
>>> print(denc)
b'\x0c\x97\x8e\x1b\xa9\x10a\n\x07\xde\x16\xa3\xf7\x10\x9f5'
>>> len(denc)
16

【讨论】:

  • 好的,谢谢大家,我现在知道了,它使用 bas64 作为输入!
  • 似乎我无法在堆栈溢出时以低于 15 的声誉投票?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-14
  • 2019-03-24
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
  • 2012-05-16
  • 1970-01-01
相关资源
最近更新 更多