我正在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形式的可读形式。
关于python - 如何在Django模型中存储密文,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34057451/