为什么我无法解密用pycrypto加密的内容?

时间:2016-04-01 19:09:08

标签: python pycrypto

这是我的代码:

加密:

from Crypto.Cipher import AES
import base64

def encryption (privateInfo):
    BLOCK_SIZE = 16
    PADDING = '{'
    pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING
    EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
    secret = 'Fr3@k1nP@ssw0rd.'
    print('encryption key:', secret)
    cipher = AES.new(secret)
    encoded = EncodeAES(cipher, privateInfo)
    print('Encrypted string:', encoded)

encryption('secret')

加密字符串为:b' QuCzNmwiVaq1uendvX7P + g =='

解密:

from Crypto.Cipher import AES
import base64

def decryption(encryptedString):
    PADDING = '{'
    DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)
    key = 'Fr3@k1nP@ssw0rd.'
    cipher = AES.new(key)
    decoded = DecodeAES(cipher, encryptedString)
    print(decoded)

decryption("b'QuCzNmwiVaq1uendvX7P+g=='")

结果:

ValueError: Input strings must be a multiple of 16 in length

这是Python 3.4上的PyCrypto 2.6.1;我也安装了VC ++ 2010 Express。 让我感到困惑的是它在Python 2.7上完美运行

任何建议都表示赞赏,但请注意我是Python的新手。

2 个答案:

答案 0 :(得分:1)

After some research and a lot of coding, testing and improving, I made this code running on Python 3.4.4 and Windows 10:

import base64
from Crypto.Cipher import AES
from Crypto.Hash import SHA256

PAD = "X"

def key_hash(key):
    return SHA256.new(key.encode()).digest()

def encrypt(text, key):
    while len(text) % 16 != 0:
        text += PAD
    cipher = AES.new(key_hash(key))
    encrypted = cipher.encrypt(text.encode())
    return base64.b64encode(encrypted).decode()

def decrypt(text, key):
    cipher = AES.new(key_hash(key))
    plain = cipher.decrypt(base64.b64decode(text))
    return plain.decode().rstrip(PAD)

if __name__ == '__main__':
    e = encrypt("This is my string.", "password")
    p = decrypt(e, "password")
    print("Encrypted:", e)
    print("Plain:", p)

Output:

Encrypted: QjkhFlXG2tklZQgHorpAOFSTb2vYZLNb/eEUIvAsT1g=
Plain: This is my string.

If you have any questions/improvements/critics, feel free to comment!

答案 1 :(得分:0)

也许是因为"周围"b'QuCzNmwiVaq1uendvX7P+g=='"

更改

decryption("b'QuCzNmwiVaq1uendvX7P+g=='")

decryption(b'QuCzNmwiVaq1uendvX7P+g==')

你应该全力以赴。