2020-02-27 Django 前端应用层密码加密 RSA

2020-02-27  本文已影响0人  多吃水果少吃肉

背景

RSA算法是当今使用最广泛,安全度最高的加密算法。

根据百科介绍,对极大整数做因数分解的难度决定了RSA算法的可靠性。换言之,对一极大整数做因数分解愈困难,RSA算法愈可靠。假如有人找到一种快速因数分解的算法的话,那么用RSA加密的信息的可靠性就肯定会极度下降。但找到这样的算法的可能性是非常小的。今天只有短的RSA钥匙才可能被强力方式解破。到目前为止,世界上还没有任何可靠的攻击RSA算法的方式。只要其钥匙的长度足够长,用RSA加密的信息实际上是不能被解破的。

通常使用公钥进行加密,使用私钥进行解密。
如上所说,钥匙的长度尽量设置长一些,在实际应用过程中,通常设置为1024或2048

前端使用js库: https://github.com/travist/jsencrypt

后端使用库:pip install pycrypto

基本逻辑

浏览器请求页面---后端把公钥传递给前端--前端js代码利用公钥加密敏感信息传递给后端--后端使用私钥解密获得数据

自己生成密钥对

from Crypto import Random
from Crypto.PublicKey import RSA

random_generator = Random.new().read
rsa = RSA.generate(1024, random_generator)
rsa_private_key = rsa.exportKey()
with open('private.pem', 'w') as f:
    f.write(rsa_private_key.decode())
rsa_public_key = rsa.publickey().exportKey()
with open('public.pem', 'w') as f:
    f.write(rsa_public_key.decode())

然后从文件种拷贝密钥对到 setting.py 文件中, 按照我示例格式哦

后端配置:

settinigs.py

RSA_PUBLIC_KEY = "<自己生成的公钥 (调整为一行,不含-----包裹的部分)>"

RSA_PRIVATE_KEY = "-----BEGIN RSA PRIVATE KEY-----\n" + "<自己生成的私钥 (调整为一行,不含-----包裹的部分)>" + "\n-----END RSA PRIVATE KEY-----"

后端渲染页面

public_key = settings.RSA_PUBLIC_KEY
            return render(request, "article/login.html", {'public_key': public_key})

前端页面js

    function doLogin() {
        var password_old = $("#MemberPassword").val();
        var encrypt = new JSEncrypt();
        encrypt.setPublicKey("{{ public_key|safe }}");
        var pass_new = encrypt.encrypt(password_old);
        $("#MemberPassword").val(pass_new);
        $("#login_button").submit();
    }

把这个按钮放到表单外面

<button class="layui-btn" style="margin-top: 15px;" onclick="doLogin()">登录</button>

这样,点击登录按钮就会重新生成加密密码填写到表单中,然后提交

后端接收解密

password = request.POST.get("password", '')
password = decrypt_pass(password).decode()

其中解密函数

from Crypto import Random
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5, PKCS1_OAEP
from django.conf import settings
import base64


def decrypt_pass(password):
    random_generator = Random.new().read
    RSA.generate(1024, random_generator)
    rsakey = RSA.importKey(settings.RSA_PRIVATE_KEY)
    cipher = PKCS1_v1_5.new(rsakey)
    return cipher.decrypt(base64.b64decode(password), random_generator)

接下来验证密码就好了。

参考资料

http://blog.nsfocus.net/python-js-encrypts-post-form-data-rsa-algorithm/
https://www.cnblogs.com/himismad/p/9722419.html

上一篇 下一篇

猜你喜欢

热点阅读