【问题标题】:How to store cipher text in Django Models如何在 Django 模型中存储密文
【发布时间】:2015-12-03 03:37:34
【问题描述】:

我正在 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': , “加密消息”: u'\ufffdH\x060\ufffd!W\ufffdooK8\ufffdg\ufffd\ufffd\ufffd\ufffd', “散列消息”: u'8ada92984f1fc55010c4d2fa38d0fba499691bc746f83eff089ba5212a65f083a947aa1fe6209f05278a5dc7ee12b361'}

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

【问题讨论】:

    标签: python django django-models cryptography pycrypto


    【解决方案1】:

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

    【讨论】:

    • 'str' object has no attribute 'base64' 收到此错误!
    • 我正在考虑将密文转换为hexcode 并保存到我的数据库中。但问题是如何将hexcode重新转换成密文进行解密?
    • base64 未解决的参考?我需要导入一些东西吗?
    • 你必须导入它。
    • 好的,import base64 在那里。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-09
    • 1970-01-01
    • 1970-01-01
    • 2022-08-16
    • 2016-02-11
    • 2019-01-01
    • 2019-10-22
    相关资源
    最近更新 更多