python Django RSA 前台加密 后端解密。

第一步    安装  pip install pycryptodomex

第二步  生成 公钥和密钥 直接运行 main方法    公钥加密  私钥解密 

"""
create_rsa_key() - 创建RSA密钥
"""
from Cryptodome import Random

from Cryptodome.PublicKey import RSA
def create_rsa_key():
    """
    创建RSA密钥
    步骤说明:
    1、从 Crypto.PublicKey 包中导入 RSA,创建一个密码
    2、生成 1024/2048 位的 RSA 密钥
    3、调用 RSA 密钥实例的 exportKey 方法,传入口令、使用的 PKCS 标准以及加密方案这三个参数。
    4、将私钥写入磁盘的文件。
    5、使用方法链调用 publickey 和 exportKey 方法生成公钥,写入磁盘上的文件。
    """
    # 利用伪随机数来生成私钥和公钥
    random_generator = Random.new().read

    key = RSA.generate(2048,random_generator) #生成 1024/2048 位的 RSA 密钥
    encrypted_key = key.exportKey() #密钥实例
    with open("my_private_rsa_key.bin", "wb") as f:#私钥写入磁盘
        f.write(encrypted_key)
    with open("my_rsa_public.pem", "wb") as f: #公钥写入磁盘
        f.write(key.publickey().exportKey())

if __name__ == '__main__':
    create_rsa_key()

生成的两个 私钥 和公钥     也可以用个变量存储。 

第三步 后台解密 

import os
from Cryptodome.PublicKey import RSA
from Cryptodome.Cipher import  PKCS1_v1_5
import base64
from urllib import parse
from django.shortcuts import render
from django.http import *
# 当前路径钥匙地址
curr_dir = os.path.dirname(os.path.realpath(__file__))
private_key_file = os.path.join(curr_dir, "my_private_rsa_key.bin") #密钥
public_key_file = os.path.join(curr_dir, "my_rsa_public.pem")  #公钥


#解码
def decrypt_data(inputdata):
    # URLDecode
    data = parse.unquote(inputdata)
    # base64decode
    data = base64.b64decode(data)
    # 读取密钥
    private_key = RSA.import_key(
        open(curr_dir + "/my_private_rsa_key.bin").read())
    # 使用 PKCS1_v1_5解密
    cipher_rsa = PKCS1_v1_5.new(private_key)
    # 当解密失败,会返回 sentinel
    sentinel = None
    ret = cipher_rsa.decrypt(data, sentinel)
    return ret.decode() #解码
#自定义注解 过滤GET和POST请求解码 。
def ouou_decode(fun):
    def check(request,*args,**kwargs):
        if "GET" == request.method:
            request.GET = request.GET.copy() #request设置可以修改
            for  i  in  list(request.GET):
                request.GET[i] = decrypt_data(request.GET[i])#解码
        elif "POST" == request.method:
            request.POST = request.POST.copy()
            for  i  in  list(request.POST):
                request.POST[i] = decrypt_data(request.POST[i])
        return fun(request, *args, **kwargs)
    return check

需要解密的方法加入 该注解,在访问方法时,根据请求判断进行解码。

第四步 前台加密和 解密    前后端 使用公钥和密钥必须一致。

<!doctype html>
<html>
  <head>
    <title>JavaScript RSA Encryption</title>
    <script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
    <script src="http://passport.cnblogs.com/scripts/jsencrypt.min.js"></script>
    <script type="text/javascript">

      $(function() {

        $('#testme').click(function() {
          // 用公钥加密
          var encrypt = new JSEncrypt();
          encrypt.setPublicKey($('#pubkey').val());
          var encrypted = encrypt.encrypt($('#input').val());
            alert('加密成功!!' +encrypted);

        // 使用私钥解密
          var decrypt = new JSEncrypt();
          decrypt.setPrivateKey($('#privkey').val());
          var uncrypted = decrypt.decrypt(encrypted);

          if (uncrypted == $('#input').val()) {
            alert('前台 解密成功!!' +uncrypted);
          }else {
            alert('解密失败!!');
          }

           encryptRequest('/json', encrypted);
        });
      });

      // 使用jsencrypt类库加密js方法,
        function encryptRequest(reqUrl, data) {
            $.ajax({
                url: reqUrl,
                type: 'get',
                data: {"data":data},
                success: function (data) {
                    alert("后台!解密成功 !!!"+data);
                },
                error: function (xhr) {
                    {#//console.error('出错了');#}
                }
            });
        }
    </script>
  </head>
  <body style="width: 1080px;margin: 0 auto">

    <label for="privkey">密钥</label><br/>
    <textarea id="privkey" rows="15" cols="65">{{ private_key }}</textarea><br/>
    <label for="pubkey">公钥</label><br/>
    <textarea id="pubkey" rows="15" cols="65">{{ public_key }}</textarea><br/>

    <label for="input">Text to encrypt:</label><br/>
    <textarea id="input" name="input" type="text" rows=4 cols=70>This is a test!</textarea><br/>
    <input id="testme" type="button" value="Test Me!!!" /><br/>
  </body>
</html>

demo下载  https://download.csdn.net/download/xianailili/10833641

猜你喜欢

转载自blog.csdn.net/xianailili/article/details/84866418