electron 集成 SQLCipher

mac

安装 brew

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

安装 sqlcipher

brew options sqlcipher
brew install sqlcipher

这部分不知道有没有起作用

export LDFLAGS="-L/usr/local/lib"
export CPPFLAGS="-I/usr/local/include -I/usr/local/include/sqlcipher"
export CXXFLAGS="$CPPFLAGS"

克隆 sqlcipher 源码,并链接

git clone https://github.com/sqlcipher/sqlcipher.git
pushd sqlcipher

make clean

./configure --enable-tempstore=yes --enable-load-extension --disable-tcl --with-crypto-lib=commoncrypto CFLAGS="-DSQLITE_HAS_CODEC -DSQLITE_ENABLE_JSON1 -DSQLITE_ENABLE_FTS3 -DSQLITE_ENABLE_FTS3_PARENTHESIS -DSQLITE_ENABLE_FTS5" LDFLAGS="-framework Security -framework Foundation"
make

成功后该文件夹下出现 .libs 隐藏文件夹

创建 custom-binding.gyp 文件

{
  "includes": [ "deps/common-sqlite.gypi" ],
  "variables": {
  },
  "targets": [
    {
      "target_name": "<(module_name)",
      "include_dirs": [
        "<!(node -e \"require('nan')\")",
        "/Users/jinghongqiu/Desktop/sqlcipher/"
      ],
      "libraries": [
        "/Users/jinghongqiu/Desktop/sqlcipher/.libs/libsqlcipher.a"
      ],
      "sources": [
        "src/database.cc",
        "src/node_sqlite3.cc",
        "src/statement.cc"
      ]
    },
    {
      "target_name": "action_after_build",
      "type": "none",
      "dependencies": [ "<(module_name)" ],
      "copies": [
          {
            "files": [ "<(PRODUCT_DIR)/<(module_name).node" ],
            "destination": "<(module_path)"
          }
      ]
    }
  ]
}

/Users/jinghongqiu/Desktop/sqlcipher 需要替换成 sqlcipher 克隆下来的路径

在 electron 项目中执行命令

echo "Copying custom binding.gyp (node-sqlite3)"
cp custom-binding.gyp node_modules/sqlite3/binding.gyp

echo "Rebuilding node-sqlite3 bindings with statically linked SQLCipher (libsqlcipher.a)"
npm rebuild sqlite3 --build-from-source --static_linking_path=/Users/jinghongqiu/Desktop/sqlcipher/.libs/libsqlcipher.a --runtime=electron --target=4.0.8 --dist-url=https://atom.io/download/electron

/Users/jinghongqiu/Desktop/sqlcipher 需要替换成 sqlcipher 克隆下来的路径
--target=4.0.8 中的数字为 electron 的版本

使用

// 在 electron 里才能使用
var sqlite3 = require('sqlite3')
var db = new sqlite3.Database('./test.sqlcipher')

db.serialize(() => {
  db.run("PRAGMA KEY = 'secret'")
  db.run("CREATE TABLE messages(id INTEGER, user VARCHAR, msg TEXT)")

  db.run("INSERT INTO messages(id, user, msg) VALUES (1, 'coolaj86', 'this is test message number one')")

  db.get("SELECT * FROM messages", (err, data) => {
    if (err) {
      console.error(err)
      return
    }
    console.log(data)
  })
})

用可视化工具打开 test.sqlcipher ,如果需要输入密码则集成成功。输入密码 secret,如果无法打开,则有可能是可视化工具问题(如 SQLiteManager 正确密码也无法打开)

参考

Building SQLCipher for node.js on Raspberry Pi 2
Setting up SQLCipher with node-sqlite3 and Electron
在 Node.js 中使用 SQLCipher

posted @ 2019-03-12 11:37  _NKi  阅读(1418)  评论(0编辑  收藏  举报