专注于 JetBrains IDEA 全家桶,永久激活,教程
持续更新 PyCharm,IDEA,WebStorm,PhpStorm,DataGrip,RubyMine,CLion,AppCode 永久激活教程

RSA 加密认证 (服务端Python3 + 客户端HTML)

39_1.png


在众多项目中都会用到用户登录认证的功能块, 作为前后端分离的项目, 保证接口敏感数据加密, 是必要的。

RSA

百度百科: RSA公开密钥密码体制是一种使用不同的加密密钥与解密密钥,“由已知加密密钥推导出解密密钥在计算上是不可行的”密码体制
baike.baidu.com/item/RSA算法/…

我们采用 Python 服务端生成密钥对(公钥和私钥), 客户端通过 API 获取公钥进行数据加密, 服务端通过私钥对加密数据进行解密验证。

服务端

生成密钥对代码块:

#!/usr/bin/env python
# _*_ Coding: UTF-8 _*_
from Crypto.PublicKey import RSA

if __name__ == '__main__':
    rsa = RSA.generate(1024)
    private_pem = str(rsa.exportKey(), encoding='utf-8')
    with open('private.pem', 'w') as f:
        f.write(private_pem)
        f.close()
    public_pem = str(rsa.publickey().exportKey(), encoding='utf-8')
    with open('public.pem', 'w') as f:
        f.write(public_pem)
        f.close()

验证加密字符代码块:

#!/usr/bin/env python
# _*_ Coding: UTF-8 _*_
import base64

from Cryptodome.Cipher import PKCS1_v1_5
from Cryptodome.PublicKey import RSA

if __name__ == '__main__':
    string = "加密的字符串"
    with open('private.pem') as file:
        key = file.read().encode()
        file.close()
    cipher = PKCS1_v1_5.new(RSA.importKey(key))
    print(cipher.decrypt(base64.b64decode(string.encode()), 'error').decode())

客户端

这儿使用的 demo 采用静态的数据, 你可以对它进行修改, 并且你可以复制以下代码块保存在 index.html 中用浏览器打开:

<!doctype html>
<html>
<head>
    <title>RSA · MedusaSorcerer</title>
    <script src="https://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
    <script src="http://passport.cnblogs.com/scripts/jsencrypt.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $('#submit').click(function () {
                var data = [];
                data['username'] = $('#username').val();
                data['password'] = $('#password').val();
                var publickey = $('#publickey').val();
                encryptSend(data, publickey);
            });
        });

        function encryptSend(data, publicKey) {
            var jsencrypt = new JSEncrypt();
            jsencrypt.setPublicKey(publicKey);
            var enData = new Object();
            for (var key in data) {
                enData[key] = jsencrypt.encrypt(data[key]);
            }
            $('.content').html(JSON.stringify(enData));
        }
    </script>
</head>
<body>
<label for="publickey">Public Key</label><br>
<textarea id="publickey" rows="10" cols="80">
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCe89pxqVioNubktqWd/1aNc+C+
IbyWB9Cuqux1ds6QTg35JDKFSUOB6VR9FoK6fDeD3DfN7UifVfAkgOz2MRq1oPJD
6+VnbjYzA6DVaN3gZ/9FjU7ZkhL+eHAgi48lALPJTGwO5nEIZIETSegpZW8HBA1k
Z9Iw0gR9zC7S0imIGQIDAQAB
-----END PUBLIC KEY-----
</textarea>
<span style="float: right;">
    <a href="https://juejin.im/user/2805609406139950/posts">
        <img src="https://user-gold-cdn.xitu.io/2019/10/13/16dc5444a4bb2dac?imageView2/1/w/180/h/180/q/85/format/webp/interlace/1"><br>
        返回 MedusaSorcerer 掘金
    </a>
</span>
<br>
<label for="input">jsencrypt:</label><br>
username: <input id="username" name="username" type="text"><br>
password: <input id="password" name="password" type="password"><br>
<input id="submit" type="button" value="submit"/>
<div style="padding-top:20px">输出内容:</div>
<div class="content" style="width:200px;height:300px;">暂无</div>
</body>
</html>

错误解决

在遇到客户端加密返回的数据是 false 的时候:

  • 服务端考虑加密密钥对格式
  • 服务端尝试更换生成密钥对的方式
  • 服务端考虑加密的 Base64.encodeBase64() 方法正确
未经允许不得转载:搜云库技术团队 » RSA 加密认证 (服务端Python3 + 客户端HTML)

JetBrains 全家桶,激活、破解、教程

提供 JetBrains 全家桶激活码、注册码、破解补丁下载及详细激活教程,支持 IntelliJ IDEA、PyCharm、WebStorm 等工具的永久激活。无论是破解教程,还是最新激活码,均可免费获得,帮助开发者解决常见激活问题,确保轻松破解并快速使用 JetBrains 软件。获取免费的破解补丁和激活码,快速解决激活难题,全面覆盖 2024/2025 版本!

联系我们联系我们