如何为加密设置正确的数据类型块大小

问题描述 投票:0回答:1

我正在尝试使用私钥和公钥加密一些纯文本。

我正在使用python,这正是我正在开始的工作。

from hashlib import md5
from base64 import b64decode
from base64 import b64encode
from Crypto import Random

BLOCK_SIZE = 16  # Bytes
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * \
                str(BLOCK_SIZE - len(s) % BLOCK_SIZE)
unpad = lambda s: s[:-ord(s[len(s) - 1:])]


class AESCipher:
    """
    Usage:
        c = AESCipher('password').encrypt('message')
        m = AESCipher('password').decrypt(c)
    Tested under Python 3 and PyCrypto 2.6.1.
    """

    def __init__(self, key):
        self.key = md5(key.encode('utf8')).hexdigest()

    def encrypt(self, raw):
        raw = pad(raw)
        iv = Random.new().read(AES.block_size)
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return b64encode(iv + cipher.encrypt(raw))

    def decrypt(self, enc):
        enc = b64decode(enc)
        iv = enc[:16]
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return unpad(cipher.decrypt(enc[16:])).decode('utf8')


##
# MAIN
# Just a test.
msg = input('Message...: ')
pwd = input('Password..: ')

c = AESCipher(pwd).encrypt(msg.encode('utf8'))
m = AESCipher(pwd).decrypt(c)

# print('Ciphertext:', AESCipher(pwd).encrypt(msg.encode('utf8')))

我在Pycharm中收到此错误

Traceback(最近一次调用最后一次): 文件“... / PycharmProjects / test / App.py”,第97行,在c = AESCipher(pwd).encrypt(msg.encode('utf8'))

在加密中文件“... / PycharmProjects / test / App.py”,第79行

raw = pad(raw)   File ".../PycharmProjects/test/App.py", line 63, in <lambda>
str(BLOCK_SIZE - len(s) % BLOCK_SIZE) TypeError: can't concat str to bytes

如何将块填充类型从str更改为byte?

python encryption cryptography pycrypto
1个回答
0
投票

你只需稍微修改你的填充功能:

pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * \
                chr(BLOCK_SIZE - len(s) % BLOCK_SIZE).encode()

请注意chr而不是str,然后该字符串需要编码为bytes

或者更好:

pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * \
                bytes((BLOCK_SIZE - len(s) % BLOCK_SIZE, ))
© www.soinside.com 2019 - 2024. All rights reserved.