Electron使用SQLite3及Sqlcipher加密

Published: 2018-08-09

Tags: Electron

本文总阅读量

(一)Electron使用SQLite3本地数据库

目前为止,最方便的使用SQLite3的方式是使用electron-builder提供重编译功能

1,添加钩子

"scripts": {
   "postinstall": "install-app-deps"
   ...
}

package.json中的script字段添加一个命令,postinstall命令是npm脚本内置的命令关键字,意思为当安装新的包后自动触发的动作,此处运行的install-app-deps命令功能是重新编译需要重编译才能在Electron下使用的包

2,安装

yarn add sqlite3

先解析包,获取,链接,编译,然后在最后,可以看到sqlite3已经被重编译

[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
[4/4] Building fresh packages...
...
$ install-app-deps
  • please use as subcommand: electron-builder install-app-deps
  • electron-builder version=20.2.0
  • loaded configuration file=package.json ("build" field)
  • rebuilding native production dependencies platform=win32 arch=ia32
  • rebuilding native dependency name=sqlite3

(二)使用Sqlcipher加密数据库

有时数据可能比较重要,不希望别人去安装目录把数据库Ctrl+C,Ctrl+V直接就拷走了,那么需要把数据库加密,至少别人直接把数据库拖到数据库管理软件里会是这样

sqlite3 Sqlcipher

从SQLite3添加扩展重编译应该是可以的,另一个法子是安装一个包@journeyapps/sqlcipher,这个包对SQLite3进行了封装,用起来很方便

Github地址:https://github.com/journeyapps/node-sqlcipher

我在使用的时候遇到一个问题,下载一个包的时候提醒403禁止访问,这很不科学,我查看到一个Issues,一位用Mac OS的人也遇到类似的问题:Pre-built Binaries Not Found. [Electron]

Windows 下安装 OpenSSL

下载页面:https://slproweb.com/products/Win32OpenSSL.html

我下载的是名为:Win64 OpenSSL v1.0.2o

安装后打开终端输入openssl看能不能找到命令,找不到则手动添加到环境变量(C:\OpenSSL-Win64\bin

再次安装

yarn add "@journeyapps/sqlcipher"

因为网络等原因,可能有ETIMEOUT报错,也可能等很长时间,Good Luck~

在Github上有代码使用示例,和原生的SQLite3使用区别仅仅是运行命令之前先输入key

db.run("PRAGMA key = 'mysecret'");

PS:一些补充

如果使用Electron,直接打包,key就存在代码中无疑是很容易就暴露的,可以考虑用javascript-obfuscator混淆一下代码,就可以很大程度的避免key泄露了。