如何加密pouchdb数据库

时间:2016-03-02 21:35:10

标签: javascript encryption browser-cache offline pouchdb

背景

我正在尝试使用crypto-pouch库加密pouchdb数据库。 我查看了https://github.com/calvinmetcalf/crypto-pouch中显示的示例 但它似乎对我没有任何作用。

我的代码:

<!DOCTYPE html>
<html ng-app="pouchdbApp">
 <head>
   <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
   <script src="pouchdbDemo.js"></script>
   <script src="http://cdn.jsdelivr.net/pouchdb/5.2.1/pouchdb.min.js"></script>
   <!-- <script src="crypto-pouch-master/bundle.js"></script> -->
   <script src="http://wzrd.in/standalone/crypto-pouch"></script>

   <script>
       var db = new PouchDB('kittens2');

       var password = "mypassword";

      db.crypto(password).then(function (publicKey) {
            console.log("publicKey");
   	    console.log(publicKey);
       });
   
       /* db.removeCrypto();  */

       var doc = {
		  "_id": "mittens",
		  "name": "Mittens",
		  "occupation": "kitten",
		  "age": 3,
		  "hobbies": [
		    "playing with balls of yarn",
		    "chasing laser pointers",
		    "lookin' hella cute"
 		   ]
		};
      
      db.put(doc);

      db.get('mittens').then(function (doc) {
         console.log(doc);
      });

   </script>

 </head>
 <body>

 </body>

</html>

但是我的代码看不到对输入的数据进行任何加密,或者我看不到任何生成的公钥。

我应该如何使用带有pouchdb的加密文件库。

2 个答案:

答案 0 :(得分:3)

编辑:这个答案最初是针对版本1.x的加密包,但对于当前版本(3.x)不正确,在当前版本中db.crypto(密码)确实如此不返回承诺,以便更新代码示例

db.crypto(password)
// <-- encryption set up

db.crypto(password);
db.put({_id: 'foo', bar: 'baz'}).then(function () {
    return db.get('foo');
}).then(function (doc) {
    console.log('decrypted', doc);
    return db.removeCrypto();
}).then(function () {
    return db.get('foo');
}).then(function (doc) {
    console.log('encrypted', doc);
})

原始回答(对v1.x仍然有效)如下:

因此文档有点令人困惑(我刚刚清理过)但是当你调用db.crypto时它会包装数据库以便文档被透明地加密和解密

db.crypto(password).then(function () {
   // <-- encryption set up
})

它将透明地加密您创建的文档并解密您阅读的文档,直到您调用

db.removeCrypto();

所以,如果你想测试做类似的事情

db.crypto(password).then(function () {
   return db.put({_id: 'foo', bar: 'baz'});
}).then(function () {
    return db.get('foo');
}).then(function (doc) {
    console.log('decrypted', doc);
    return db.removeCrypto();
}).then(function () {
    return db.get('foo');
}).then(function (doc) {
    console.log('encrypted', doc);
})

答案 1 :(得分:0)

我尝试了combDB,它是目前唯一可以与新的nodeJS一起使用的工具

const PouchDB = require('pouchdb')
PouchDB.plugin(require('comdb'))

const password = 'extremely secure value'

const db = new PouchDB(POUCH_PATH)
db.setPassword(password)

db.post({
  _id: 'gay-agenda',
  type: 'queerspiracy',
  agenda: ['be gay', 'do crimes']
}).then(() => {
  // now replicate to a couchdb instance
  return db.replicate.to(`${COUCH_URL}/FALGSC`)
})

或带有Angular(打字稿)

import PouchDB from 'pouchdb-browser';

...
 this.db = new PouchDB('myProjectDB');
 this.db.setPassword(environment.dbPassword);