最近在练习做网易云音乐项目在实现其中两个功能时遇到了一些问题,希望大佬能帮助解答
自动登录功能
实现思路
在用户登录时如果勾选了自动登录
选项,就把用户的用户名与密码以加密形式保存在本地数据库,下次用户打开应用在App.vue挂载后直接读取并解密本地的用户名与密码,然后自动调用登录接口,从而实现自动登录。
加密与解密代码
const crypto = require('crypto');
const key = crypto.randomBytes(32); // 256 位的共享密钥
const iv = crypto.randomBytes(16); // 初始向量,16 字节
const algorithm = 'aes-256-gcm'; // 加密算法和操作模式
function encode(data) {//加密算法
// data:要加密的数据
const cipher = crypto.createCipheriv(algorithm, key, iv); // 初始化加密算法
let encrypted = cipher.update(data, 'utf8', 'hex');
console.log(encrypted);
return encrypted;
}
function decode(data) {//解密算法
// data:从本地数据库中读取的加密后的数据
const decipher = crypto.createDecipheriv(algorithm, key, iv); // 初始化解密算法
let decrypted = decipher.update(data, 'hex', 'utf8');
return decrypted
}
export{
encode,
decode
}
- 本地数据库:Nedb
- 加密用的是node自带的crypto
问题
在解密保存的数据时发现无法还原,解密的结果是乱码。但是如果不将数据保存而是直接解密就没有问题。请问这是为什么?是因为Nedb以UTF-8的编码形式保存数据,而加密后的数据是hex编码形式,二者相冲突造成的么?
应用退出前保存所听的音乐
实现思路
在electron关闭时主进程向渲染进程通知渲染进程将当前的音乐信息保存到本地数据库。然后用户在下一次打开应用时直接读取。
相关代码
win = new BrowserWindow({
width: 800, height: 600, webPreferences: {
nodeIntegration: true
},
frame: false
})
...
win.on("close",()=>{
win.webContents.send("close")
})
const { ipcRenderer: ipc } = require("electron");
...
ipc.on("close", (res) => {
...
localSetting.find({ index: { $exists: true }, name: { $exists: true }, }).then(
async (musicInfo) => {
if (musicInfo.length === 0) {
//如果没有保存歌曲信息就先保存
localSetting.insert([this.$store.state.musicInfo, this.$store.state.musicTime]);
} else {
//更新保存的歌曲信息
let time = await localSetting.find({ currentTime: { $exists: true }, duration: { $exists: true }, })
localSetting.update(musicInfo[0],this.$store.state.musicInfo)
localSetting.update(time[0],this.$store.state.musicTime)
}
})
})
问题
应用关闭后并没有将音乐信息插入或者更新
有没有大佬能告诉我这两个问题产生的原因是什么,该怎么解决?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…