js & python实现RSA非对称加密

思路

一般,我们前端使用js加密数据,传递给后台服务接口,服务再进行解密得到数据信息。

  1. python生成公钥,传递给前端js
  2. 前端js使用公钥加密信息,发送给后端服务接口
  3. 后端python使用私钥解密数据

python生成秘钥

# -*- encoding:utf-8 -*-
from Crypto.PublicKey import RSA
from flask import current_app
from Crypto import Random

# rsa算法生成实例
RANDOM_GENERATOR=Random.new().read
rsa = RSA.generate(1024, RANDOM_GENERATOR)
# 生成私钥,可以存在session中
private_pem = rsa.exportKey()
# 生成公钥,传递给前端
public_pem = rsa.publickey().exportKey()

前端js加密

//导入js,如果需要base64文件,一定要在导入加密js文件之前导入,否则会出现加密结果为 false;
//如果报 typeerror-base64-not-a-constructor;使用http://blog.csdn.net/ziwoods/article/details/58595840解决方法
<script src="js/plugin/base64.js"></script>
<script src="js/plugin/jsencrypt.min.js" type="text/javascript"></script>

//获取公钥,后端获取到的
var PUBLIC_KEY = "-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCogdzMsG4S20msz32M+a1GNg2Tw4UIEGDD/dfKkoZgRtEaJtHzCXgmpP3eECHCJsK0zt0GYYxGQnfbq5mBd37xVnAlKWjVpjGQHZ+fjwn82+mRUzjmFGLs3ax79zaXJZnHTN63/yS2Rua3QY/T5Z5TLpn2YOmOn09U22eA3vdfZwIDAQAB-----END PUBLIC KEY-----";

//rsa加密
var encrypt = new JSEncrypt();
encrypt.setPublicKey(PUBLIC_KEY);
password = encrypt.encrypt(password);//加密后的字符串

后端解密

# -*- encoding:utf-8 -*-
from Crypto.PublicKey import RSA

# 可以从session中获取私钥,或统一使用同一个
private_pem = ""
rsakey = RSA.importKey(private_pem)
cipher = Cipher_pkcs1_v1_5.new(rsakey)
#使用base64解密,(在前端js加密时自动是base64加密)
password = cipher.decrypt(base64.b64decode(password), None)
#如果返回的password为None或则异常,说明秘钥公钥不一致,或者程序错误
if password is None:
    return 'fail'

测试代码

# -*- encoding:utf-8 -*-
import base64
from Crypto import Random
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
from Crypto.PublicKey import RSA

# 伪随机数生成器
random_generator = Random.new().read
# rsa算法生成实例
rsa = RSA.generate(1024, random_generator)
# 私钥是生成
private_pem = rsa.exportKey()
# 公钥生成
public_pem = rsa.publickey().exportKey()


# 用公钥加密
# 被加密的数据
message = 'I_LOVE_YAYA'
# 打开公钥文件
rsakey = RSA.importKey(public_pem)
cipher = Cipher_pkcs1_v1_5.new(rsakey)
# 加密时使用base64加密
cipher_text = base64.b64encode(cipher.encrypt(message))
# cipher_text = cipher.encrypt(message)
print cipher_text


# 用私钥解密
# 打开秘钥文件
rsakey = RSA.importKey(private_pem)
cipher = Cipher_pkcs1_v1_5.new(rsakey)
# text = cipher.decrypt(cipher_text, random_generator)
# 使用base64解密,(在前端js加密时自动是base64加密)
text = cipher.decrypt(base64.b64decode(cipher_text), None)
print text

参考

https://cloud.tencent.com/developer/article/1083580