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

时间:2019-03-11 07:24:50

标签: python encryption cryptography pycrypto

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

我正在使用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中遇到此错误

  

回溯(最近通话最近):
  文件   “ ... / 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更改为字节?

1 个答案:

答案 0 :(得分:0)

您只需要稍微修改一下填充功能:

->when

注意用pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * \ chr(BLOCK_SIZE - len(s) % BLOCK_SIZE).encode() 代替chr,然后将字符串编码为str

也许更好:

bytes