有时,我们需要加密Django应用程序中的关键信息。例如,客户端可能要求您以加密格式存储用户信息,以增加安全性。或者,您可能需要以加密格式在URL中传递一些数据。
在这里,我们将看到如何加密和解密Django中的信息。
的初始设置完成后,工程项目并添加了第一个应用程序,创建了一个新目录,或者添加了一个名为python的新包。效用在你的应用程序里。
创造_文件在实用程序目录中。添加一个新文件,命名为加密util.py在实用程序目录中。
入门Python其实很容易,但是我们要去坚持学习,每一天坚持很困难,我相信很多人学了一个星期就放弃了,为什么呢?
加密:
添加一个新函数来加密所提供的内容。使用下面的代码。每一行都由所附注释解释。
def encrypt(txt):
try:
# convert integer etc to string first
txt=str(txt)
# get the key from settings
cipher_suite=Fernet(settings.ENCRYPT_KEY) # key should be byte
# #input should be byte, so convert the text to byte
encrypted_text=cipher_suite.encrypt(txt.encode('ascii'))
# encode to urlsafe base64 format
encrypted_text=base64.urlsafe_b64encode(encrypted_text).decode("ascii")
return encrypted_text
except Exception as e:
# log the error if any
logging.getLogger("error_logger").error(traceback.format_exc())
return None
请注意:
-加密密钥应保持安全。留着 settings_production.py 文件,不要将其提交给git。
-我们还将编码的字符串转换为URL安全base 64格式,因为我们可能需要将全日制编码的数据传递给URL。
-如果有错误,记录它并返回NULL。
解密:
要解密任何加密的文本,我们只需逆转这个过程。
def decrypt(string):
try:
# base64 decode
txt=base64.urlsafe_b64decode(txt)
cipher_suite=Fernet(settings.ENCRYPT_KEY)
decoded_text=cipher_suite.decrypt(txt).decode("ascii")
return decoded_text
except Exception as e:
# log the error
logging.getLogger("error_logger").error(traceback.format_exc())
return None依赖性:
您需要在python模块下面安装。
-密码学
钥匙:
您需要使用下面的进程生成Encrypt_Key。
-在安装加密python模块的虚拟环境中打开终端。
-进口Fernet。
from cryptography.fernet import Fernet
-生成密钥。
Fernet.generate_key()
-将密钥保存在设置文件中。
ENCRYPT_KEY=b'iDJpljxUBBsacCZ50GpSBff6Xem0R-giqXXnBFGJ2Rs='
用法:
在第一步创建的实用程序包中,我们创建了
___
档案。在此文件中添加以下语句。
from .encryption_util import *
现在,在视图中使用加密和解密方法。
encryption_util.encrypt(username)完整代码:
的完整代码
加密util.py
在下面。
from cryptography.fernet import Fernet
import base64
import logging
import traceback
from django.conf import settings
#this is your "password/ENCRYPT_KEY". keep it in settings.py file
#key=Fernet.generate_key()
def encrypt(txt):
try:
# convert integer etc to string first
txt=str(txt)
# get the key from settings
cipher_suite=Fernet(settings.ENCRYPT_KEY) # key should be byte
# #input should be byte, so convert the text to byte
encrypted_text=cipher_suite.encrypt(txt.encode('ascii'))
# encode to urlsafe base64 format
encrypted_text=base64.urlsafe_b64encode(encrypted_text).decode("ascii")
return encrypted_text
except Exception as e:
# log the error if any
logging.getLogger("error_logger").error(traceback.format_exc())
return None
def decrypt(txt):
try:
# base64 decode
txt=base64.urlsafe_b64decode(txt)
cipher_suite=Fernet(settings.ENCRYPT_KEY)
decoded_text=cipher_suite.decrypt(txt).decode("ascii")
return decoded_text
except Exception as e:
# log the error
logging.getLogger("error_logger").error(traceback.format_exc())
return None