这里我没有做获取key的接口,而是用socket.io自定义一个事件,来触发生成公匙。如图
1.pip安装flask-socket
2.注册handle_key事件
3.监听key事件,并生成公匙、私匙,这里可以保存在自己数据库,也可以保存成pem文件,注意python要安装对应的库
4.监听login事件,并用私匙解密,完成登录!
这里我暂未写完解密,待以后补充…
5.vue前端用获取的公匙加密登录信息:
npm安装jsencrypt
也可以直接引入
下面是vuesocketio的配置,链接服务器,端口由后端决定
在onload中加入监听socket事件和获取key的socket请求
this.$socket.emit('key', '');
this.sockets.subscribe('key', (data) => {
this.key = data
});
this.sockets.subscribe('message', (data) => {
this.msg(data)
});
this.sockets.subscribe('msg', (data) => {
console.log(data)
data = JSON.parse(data)
this.msg(data.msg,data.type)
});
获取到后台的公匙之后用jsencrypt加密登录信息
if(this.user == '' || this.pwd == ''){
return this.msg('账号密码不能为空','error')
}
let that = this
let encryptor = new JSEncrypt() // 新建JSEncrypt对象
let publicKey = this.key
encryptor.setPublicKey(publicKey) // 设置公钥
var rsaPwd = encryptor.encrypt(that.pwd) // 对需要加密的数据进行加密
// var rsaPwd = this.$rsaCrypto(publicKey,that.pwd)
this.$socket.emit('login', {pwd:rsaPwd,user:this.user})
from flask import Flask, render_template
from flask_socketio import SocketIO, send, emit, ConnectionRefusedError, Namespace
import sys
from Crypto import Random
import json
from Crypto.PublicKey import RSA
print(sys.version)
print(sys.getdefaultencoding())
print(sys.getfilesystemencoding())
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
@socketio.on('connect')
def test_connect():
emit('my response', {'data': 'Connected'})
print('Client connect')
@socketio.on('disconnect')
def test_disconnect():
print('Client disconnected')
@socketio.on('message')
def handle_message(message):
print('received login: ' + str(message))
def handle_key(message):
print('received key:' + str(message))
socketio.on_event('key', handle_key, namespace='/chat')
def handle_login(message):
print('received login: ' + str(message))
socketio.on_event('login', handle_login, namespace='/chat')
@socketio.on('login')
def handle_login(message):
emit('msg', json.dumps({'type': 'success', 'msg': '登录成功'}, ensure_ascii=False))
print(json.dumps({'type': 'success', 'msg': '登录成功'}, ensure_ascii=False))
@socketio.on('key')
def handle_key(message):
RANDOM_GENERATOR = Random.new().read
rsa = RSA.generate(1024, RANDOM_GENERATOR)
# master的秘钥对的生成
PRIVATE_PEM = rsa.exportKey()
with open('master-private.pem', 'w') as f:
f.write(PRIVATE_PEM.decode('utf-8'))
print
PRIVATE_PEM
PUBLIC_PEM = rsa.publickey().exportKey()
print
PUBLIC_PEM
with open('master-public.pem', 'w') as f:
f.write(PUBLIC_PEM.decode('utf-8'))
emit('key', PUBLIC_PEM.decode('utf-8'))
if __name__ == '__main__':
socketio.run(app)