在众多项目中都会用到用户登陆认证的功能块, 做为先后端分离的项目, 保证接口敏感数据加密, 是必要的。javascript
百度百科: RSA公开密钥密码体制是一种使用不一样的加密密钥与解密密钥,“由已知加密密钥推导出解密密钥在计算上是不可行的”密码体制
baike.baidu.com/item/RSA算法/…html
咱们采用 Python 服务端生成密钥对(公钥和私钥), 客户端经过 API 获取公钥进行数据加密, 服务端经过私钥对加密数据进行解密验证。java
生成密钥对代码块:python
#!/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()
复制代码
验证加密字符代码块:jquery
#!/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
中用浏览器打开:web
<!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/5da32395e51d4578200cc9c5/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()
方法正确