RSA 加密认证 (服务端Python3 + 客户端HTML)
站长
· 阅读数 20
在众多项目中都会用到用户登录认证的功能块, 作为前后端分离的项目, 保证接口敏感数据加密, 是必要的。
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
中用浏览器打开:
错误解决
在遇到客户端加密返回的数据是 false
的时候:
- 服务端考虑加密密钥对格式
- 服务端尝试更换生成密钥对的方式
- 服务端考虑加密的
Base64.encodeBase64()
方法正确