使用Crypto进行DES解码发生错误,错误信息为ValueError: Incorrect DES key length (24 bytes)。
encoding='utf-8'
from Crypto.Cipher import DES
def decode_char(c):
if c == 'a':
r = '?'
else:
r = c
return ord(r) - ord('!')
def ascii_to_binary(s):
assert len(s) == 24
out = [0]*18
i = 0
j = 0
for i in range(0, len(s), 4):
y = decode_char(s[i + 0])
y = (y << 6) & 0xffffff
k = decode_char(s[i + 1])
y = (y | k) & 0xffffff
y = (y << 6) & 0xffffff
k = decode_char(s[i + 2])
y = (y | k) & 0xffffff
y = (y << 6) & 0xffffff
k = decode_char(s[i + 3])
y = (y | k) & 0xffffff
out[j+2] = chr(y&0xff)
out[j+1] = chr((y>>8) & 0xff)
out[j+0] = chr((y>>16) & 0xff)
j += 3
return "".join(out)
def decrypt_password(p):
r = ascii_to_binary(p)
r = r[:16]
d = DES.new("x01x02x03x04x05x06x07x08", DES.MODE_ECB)
r = d.decrypt(r)
return r.rstrip("x00")
if __name__ == '__main__':
miwen = "_WJ(L-<*DP9QC-&C&\"^8CQ!!"
print('明文'+decrypt_password(miwen))
C:\Users\Administrator>python d:\python\h1.py
Traceback (most recent call last):
File "d:\python\h3c1.py", line 50, in <module>
print('明文'+decrypt_password(miwen))
^^^^^^^^^^^^^^^^^^^^^^^
File "d:\python\h3c1.py", line 44, in decrypt_password
d = DES.new("x01x02x03x04x05x06x07x08", DES.MODE_ECB)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\lib\site-packages\Crypto\Cipher\DES.py", line 145, in new
return _create_cipher(sys.modules[__name__], key, mode, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\lib\site-packages\Crypto\Cipher\__init__.py", line 79, in _create_cipher
return modes[mode](factory, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\lib\site-packages\Crypto\Cipher\_mode_ecb.py", line 216, in _create_ecb_cipher
cipher_state = factory._create_base_cipher(kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\lib\site-packages\Crypto\Cipher\DES.py", line 70, in _create_base_cipher
raise ValueError("Incorrect DES key length (%d bytes)" % len(key))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: Incorrect DES key length (24 bytes)
C:\Users\Administrator>
找出原因,让程序运行.
把报错代码发给我看一下