如何在 Django 模型中存储密文

How to store cipher text in Django Models

我正在 Django 1.8 中开发 Cryptography Application 并尝试将 Cipher Text 存储在我的模型字段中。下面是我的 Message 模型:

class Message(models.Model):
    user_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user_name = models.ForeignKey(User)
    message = models.TextField()
    encrypted_message = models.CharField(max_length=200, null=True, blank=True)
    hashed_message = models.CharField(max_length=100, null=True, blank=True)

    def __unicode__(self):
        return unicode(self.user_id)

我在 Python 中使用以下 pycrypto 模块来加密消息并将密文存储在我的 Django 模型中。

加解密代码在这里:

from Crypto.Cipher import AES
# Encryption

encryption_suite = AES.new('This is a key123', AES.MODE_CFB, 'This is an IV456')
cipher_text = encryption_suite.encrypt("Life is Beautiful")

# Decryption

decryption_suite = AES.new('This is a key123', AES.MODE_CFB, 'This is an IV456')
plain_text = decryption_suite.decrypt(cipher_text)

现在假设User输入一条消息My life is Beautiful,那么您可以看到加密后的消息将是:

'encrypted_message':
> u'\ufffdH\x060\ufffd!W\ufffdooK8\ufffdg\ufffd\ufffd\ufffd\ufffd',

{'message': u'Life is beautiful ', 'user_name': , 'encrypted_message': u'\ufffdH\x060\ufffd!W\ufffdooK8\ufffdg\ufffd\ufffd\ufffd\ufffd', 'hashed_message': u'8ada92984f1fc55010c4d2fa38d0fba499691bc746f83eff089ba5212a65f083a947aa1fe6209f05278a5dc7ee12b361'}

但问题是当我将这个 Cipher Text 存储在我的模型中时,它会出现一些我无法再次 decrypt 的奇怪字符。任何人都可以帮助我如何将 cipher text 存储在我的模型字段中然后 decrypt 它。

您可以使用 base64.b64encode()base64.b64decode() 将超文本转换为不会破坏 HTML 形式的可读形式。