简体   繁体   English

无法使用 pycrypto AES 加密带有特殊字符的字符串

[英]Cant encrypt strings with special characters with pycrypto AES

Description描述

I want to store people's names in MySQL database.我想将人名存储在 MySQL 数据库中。 Because the data is sensitive information i want to encrypt it with AES.因为数据是敏感信息,所以我想用 AES 加密它。 I am using PyCrypto AES module.我正在使用PyCrypto AES模块。 The code that I am using is:我正在使用的代码是:

class AESCipher(object):

    def __init__(self, key):
        self.bs = 64
        self.key = hashlib.sha256(key.encode()).digest()

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

    def decrypt(self, enc):
        enc = base64.b64decode(enc)
        iv = enc[:AES.block_size]
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return self._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8')

    def _pad(self, s):
        return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)

    @staticmethod
    def _unpad(s):
        return s[:-ord(s[len(s)-1:])]

operator = AESCipher(data_encryption_key)

The key used for encryption is a random long string.用于加密的密钥是一个随机的长字符串。

Problem问题

Lets say the string (example name) i want to encrypt is "Strah".假设我要加密的字符串(示例名称)是“Strah”。 I get the folowing cipher text.我得到以下密文。

b'kA/Q5snPUHltzh3Kl8QMH/uTpfcjdXtvrx0JUrGv2tk+P86ERfkv0eTBV5j6MThkKplLLcn4f1Ei4Q1gT/FcVx+PhEnqczKhuvLzrLHYlQ4='

But if the name includes some special characters like č,š or ž and i want to encrypt a name like "Štrah" i will get the following error:但是,如果名称包含一些特殊字符,例如 č、š 或 ž,并且我想加密像“Štrah”这样的名称,我将收到以下错误:

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

So the question is, what should I do to encrypt strings with special characters.所以问题是,我应该怎么做才能用特殊字符加密字符串。

The problem here is that the cipher internally operates on bytes, but you're giving it a string. 这里的问题是密码在内部对字节进行操作,但是你给它一个字符串。 You're padding the string to a multiple of 16, but when that string is encoded to bytes, it's no longer a multiple a 16. 您将字符串填充为16的倍数,但是当该字符串被编码为字节时,它不再是16的倍数。

>>> text = 'Štrah'
>>> padded = AESCipher('')._pad(raw)
>>> len(padded)
64
>>> len(padded.encode('utf8'))
65

The solution is to encode the string yourself instead of letting the cipher do it for you. 解决方案是自己编码字符串,而不是让密码为你做。 You have to make 2 small changes: 你必须做两个小改动:

def encrypt(self, raw):
    raw = raw.encode('utf8')  # encode to bytes here
    raw = self._pad(raw)
    iv = Random.new().read(AES.block_size)
    cipher = AES.new(self.key, AES.MODE_CBC, iv)
    return base64.b64encode(iv + cipher.encrypt(raw))

def _pad(self, s):
    # pad with bytes instead of str
    return s + (self.bs - len(s) % self.bs) * \
           chr(self.bs - len(s) % self.bs).encode('utf8')
import codecs
from Cryptodome.Util.Padding import pad, unpad
from Cryptodome.Cipher import AES

key = "key"
keys = bytes(key, 'utf-8')
key = keys + b"\0" * (16 - len(keys) % 16)


class crypto:

    def encrypt(data):
        cipher1 = AES.new(key, AES.MODE_ECB)
        ciphertext = cipher1.encrypt(pad(data.encode(), 16))
        encrypted_data = codecs.encode(ciphertext, 'hex')
        encrypted_data = encrypted_data.decode('utf-8')
        encrypted_data = encrypted_data.upper()
        return encrypted_data

    def decrypt(ciphertext):
        ciphertext = codecs.decode(ciphertext, 'hex')
        cipher2 = AES.new(key, AES.MODE_ECB)
        plaintext2 = unpad(cipher2.decrypt(ciphertext), 16)
        decrypted_data = plaintext2.decode()
        return decrypted_data

data = "à, è, ì, ò, ùÀ, È, Ì, Ò, Ù(ACCENT GRAVE), the letterá, é, í, ó, ú, ýÁ, É, Í, Ó, Ú, Ý(APOSTROPHE), the letterâ, ê, î, ô, ûm Ä, Ë, Ï, Ö, Ü, Ÿ"

encryped_data= crypto.encrypt(data)
print(encryped_data)

decrypted_data = crypto.decrypt(encryped_data)
print(decrypted_data)

Use This function to AES encrypt decrypt the accent letters and special char letters with the equivalent of MySQL AES encrypt decrypt使用此 function 对重音字母和特殊字符字母进行 AES 加密解密,等效于 MySQL AES 加密解密

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM