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

3,861 阅读1分钟

MedusaSorcerer的博客


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

RSA

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

我们采用 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.cn/user/2805609406139950">
        <img src="https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2019/10/13/16dc5444a4bb2dac~tplv-t2oaga2asx-image.image"><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() 方法正确