Python Crypto - 示例脚本说明

时间:2014-09-09 21:29:42

标签: python

我一直试图弄清楚为什么下面的代码无法用16字节填充IV。我已经看过加密文档,但我不是更明智的。我在网上找到了一些例子,但我没有看到下面的代码和工作示例(在Ruby中)的差异。任何帮助将不胜感激。

import sys
from Crypto.Cipher import AES
from base64 import b64decode

key = """
4e 99 06 e8  fc b6 6c c9  fa f4 93 10  62 0f fe e8
f4 96 e8 06  cc 05 79 90  20 9b 09 a4  33 b6 6c 1b
"""
key.replace(" ","").replace("\n","").decode('hex')

password1 = "j1Uyj3Vx8TY9LtLZil2uAuZkFQA/4latT76ZwgdHdhw"
password1 += "=" * ((4 - len(password1) % 4) % 4)
password = b64decode(password1)

o = AES.new(key, AES.MODE_CBC).decrypt(password)

print o[:-ord(o[-1])].decode('utf16')

2 个答案:

答案 0 :(得分:0)

不确定这是否是您的问题,但您可能会输入错字。 :) password2我应该阅读password1

答案 1 :(得分:0)

from Crypto.Cipher import AES
import base64

def rpad(s, fill='=', multiple=8):
    """
    Pad s with the fill char so the length of the string 
    is a multiple of `multiple` (default 8).
    """
    return s + fill * (-len(s) % multiple)

key = """
4e 99 06 e8  fc b6 6c c9  fa f4 93 10  62 0f fe e8
f4 96 e8 06  cc 05 79 90  20 9b 09 a4  33 b6 6c 1b
"""
key = key.replace(" ","").replace("\n","").decode('hex')

mode = AES.MODE_CBC
iv = "\x00"*16
enc = AES.new(key, mode, iv)

password = "j1Uyj3Vx8TY9LtLZil2uAuZkFQA/4latT76ZwgdHdhw"
decoded = base64.b64decode(rpad(password, multiple=4))

o = enc.decrypt(decoded)
print(o[:-ord(o[-1])].decode('utf16'))

打印

Local*P4ssword!

  • 正如Jon Clements所指出的,key.replace(...)返回一个字符串。您需要重新分配该字符串 至key,否则替换完成无效。