Browse Source

testing openpgp encryption

rohit.gowda 4 years ago
parent
commit
57b5ce6841

+ 1 - 0
app/package.json

@@ -54,6 +54,7 @@
     "ionicons": "3.0.0",
     "javascript-time-ago": "^1.0.34",
     "node-rsa": "^1.0.2",
+    "openpgp": "^4.7.1",
     "rxjs": "5.5.11",
     "sw-toolbox": "3.6.0",
     "twit": "^2.2.11",

File diff suppressed because it is too large
+ 21544 - 0
app/src/assets/scripts/openpgp.js


+ 145 - 0
app/src/assets/scripts/openpgp.worker.js

@@ -0,0 +1,145 @@
+(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
+// GPG4Browsers - An OpenPGP implementation in javascript
+// Copyright (C) 2011 Recurity Labs GmbH
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 3.0 of the License, or (at your option) any later version.
+//
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+/* eslint-disable no-restricted-globals */
+/* eslint-disable no-var */
+/* eslint-disable vars-on-top */
+
+/**
+ * @fileoverview Provides functions for communicating with workers
+ * @see module:openpgp.initWorker
+ * @see module:openpgp.getWorker
+ * @see module:openpgp.destroyWorker
+ * @see module:worker/async_proxy
+ * @module worker/worker
+ */
+
+self.window = self; // to make UMD bundles work
+
+importScripts('openpgp.js');
+var openpgp = window.openpgp;
+
+var randomQueue = [];
+var MAX_SIZE_RANDOM_BUFFER = 60000;
+
+/**
+ * Handle random buffer exhaustion by requesting more random bytes from the main window
+ * @returns {Promise<Object>}  Empty promise whose resolution indicates that the buffer has been refilled
+ */
+function randomCallback() {
+
+  if (!randomQueue.length) {
+    self.postMessage({ event: 'request-seed', amount: MAX_SIZE_RANDOM_BUFFER });
+  }
+
+  return new Promise(function(resolve) {
+    randomQueue.push(resolve);
+  });
+}
+
+openpgp.crypto.random.randomBuffer.init(MAX_SIZE_RANDOM_BUFFER, randomCallback);
+
+/**
+ * Handle messages from the main window.
+ * @param  {Object} event   Contains event type and data
+ */
+self.onmessage = function(event) {
+  var msg = event.data || {};
+
+  switch (msg.event) {
+    case 'configure':
+      configure(msg.config);
+      break;
+
+    case 'seed-random':
+      seedRandom(msg.buf);
+
+      var queueCopy = randomQueue;
+      randomQueue = [];
+      for (var i = 0; i < queueCopy.length; i++) {
+        queueCopy[i]();
+      }
+
+      break;
+
+    default:
+      delegate(msg.id, msg.event, msg.options || {});
+  }
+};
+
+/**
+ * Set config from main context to worker context.
+ * @param  {Object} config   The openpgp configuration
+ */
+function configure(config) {
+  Object.keys(config).forEach(function(key) {
+    openpgp.config[key] = config[key];
+  });
+}
+
+/**
+ * Seed the library with entropy gathered window.crypto.getRandomValues
+ * as this api is only avalible in the main window.
+ * @param  {ArrayBuffer} buffer   Some random bytes
+ */
+function seedRandom(buffer) {
+  if (!(buffer instanceof Uint8Array)) {
+    buffer = new Uint8Array(buffer);
+  }
+  openpgp.crypto.random.randomBuffer.set(buffer);
+}
+
+/**
+ * Generic proxy function that handles all commands from the public api.
+ * @param  {String} method    The public api function to be delegated to the worker thread
+ * @param  {Object} options   The api function's options
+ */
+function delegate(id, method, options) {
+  if (typeof openpgp[method] !== 'function') {
+    response({ id:id, event:'method-return', err:'Unknown Worker Event' });
+    return;
+  }
+  // construct ReadableStreams from MessagePorts
+  openpgp.util.restoreStreams(options);
+  // parse cloned packets
+  options = openpgp.packet.clone.parseClonedPackets(options, method);
+  openpgp[method](options).then(function(data) {
+    // clone packets (for web worker structured cloning algorithm)
+    response({ id:id, event:'method-return', data:openpgp.packet.clone.clonePackets(data) });
+  }).catch(function(e) {
+    openpgp.util.print_debug_error(e);
+    response({
+      id:id, event:'method-return', err:e.message, stack:e.stack
+    });
+  });
+}
+
+/**
+ * Respond to the main window.
+ * @param  {Object} event  Contains event type and data
+ */
+function response(event) {
+  self.postMessage(event, openpgp.util.getTransferables(event.data, true));
+}
+
+/**
+ * Let the main window know the worker has loaded.
+ */
+postMessage({ event: 'loaded' });
+
+},{}]},{},[1]);

+ 2 - 0
app/src/index.html

@@ -17,6 +17,8 @@
 
   <!-- cordova.js required for cordova apps (remove if not needed) -->
   <script src="cordova.js"></script>
+  <script src="assets/scripts/openpgp/openpgp.js"></script>
+  <script src="assets/scripts/openpgp/openpgp.worker.js"></script>
 
   <!-- un-comment this code to enable service worker
   <script>

+ 71 - 1
app/src/pages/write-tweet/write-tweet.ts

@@ -19,6 +19,7 @@ import { P2pStorageIpfsProvider } from "../../providers/p2p-storage-ipfs/p2p-sto
 import { P2pDatabaseGunProvider } from "../../providers/p2p-database-gun/p2p-database-gun";
 import twittertext from "twitter-text";
 import { CryptoProvider } from "../../providers/crypto/crypto";
+import * as openpgp from 'openpgp';
 
 @IonicPage()
 @Component({
@@ -31,6 +32,11 @@ export class WriteTweetPage {
   replyToStatusId: string;
   retweet;
   replyTweet;
+  openpgp;
+  privateKey;
+  publicKey;
+  passp = 'super long and hard to guess secret' ;
+ 
 
   constructor(
     public navCtrl: NavController,
@@ -53,8 +59,72 @@ export class WriteTweetPage {
     });
 
     this.addValidators();
+    
+    this.generateKeys();
   }
 
+   public async encryptDecryptFunction () {
+    // await openpgp.initWorker({});
+    // await this.generateKeys();
+    console.log('priv key: ',this.privateKey,'this . pubkey',this.publicKey);
+    let encrypted;
+    const privKeyObj = (await openpgp.key.readArmored(this.privateKey)).keys[0];
+    console.log('privKeyObj',privKeyObj);
+    await privKeyObj.decrypt(this.passp)
+
+    const options = {
+        message: openpgp.message.fromText('Hello, World!'),       // input as Message object
+        publicKeys: (await openpgp.key.readArmored(this.publicKey)).keys, // for encryption
+        privateKeys: [privKeyObj]                                 // for signing (optional)
+    }
+
+    openpgp.encrypt(options).then(ciphertext => {
+        encrypted = ciphertext.data // '-----BEGIN PGP MESSAGE ... END PGP MESSAGE-----'
+        console.log('encrypted text is:',encrypted);
+        return encrypted
+    })
+    .then(async encrypted => {
+        const options = {
+            message: await openpgp.message.readArmored(encrypted),    // parse armored message
+            publicKeys: (await openpgp.key.readArmored(this.publicKey)).keys, // for verification (optional)
+            privateKeys: [privKeyObj]                                 // for decryption
+        }
+
+        openpgp.decrypt(options).then(plaintext => {
+        console.log('decrypted text is:',plaintext,plaintext.data);
+            return plaintext.data // 'Hello, World!'
+        })
+
+    })
+  }
+
+  public async generateKeys(){
+    let options = {
+      userIds: [{ name:'Jon Smith', email:'jon@example.com' }], // multiple user IDs
+      curve: "ed25519",                                         // ECC curve name
+      passphrase: this.passp        // protects the private key
+    };
+   
+      // var vm = this;
+      // openpgp.generateKey(options)
+      // .then(function(vm,key) {
+      //   if(key){
+      //     var privkey = key.privateKeyArmored; // '-----BEGIN PGP PRIVATE KEY BLOCK ... '
+      //     var pubkey = key.publicKeyArmored;   // '-----BEGIN PGP PUBLIC KEY BLOCK ... '
+      //     var revocationCertificate = key.revocationCertificate; // '-----BEGIN PGP PUBLIC KEY BLOCK ... '
+      //     vm.privateKey =privkey;
+      //     vm.publicKey = pubkey;
+      //   }
+      // })
+
+      const a = await openpgp.generateKey(options);
+      console.log('resolved a = ',a);
+          this.privateKey =a.privateKeyArmored;
+          this.publicKey = a.publicKeyArmored;
+          this.encryptDecryptFunction();
+  }
+
+
   private async addValidators() {
     const triggerWords = await this.storage.get("keywords");
     const validators = [
@@ -132,7 +202,7 @@ export class WriteTweetPage {
       ) {
         loading.setContent("Publish private tweet...");
         await this.tweetPrivate();
-      } else {
+        } else {
         loading.dismiss();
         const alert = this.alertCtrl.create({
           title: "Oooops...",

+ 1 - 0
dashboard/index.html

@@ -87,6 +87,7 @@
     </div>
   </div>
 
+  
   <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>

Some files were not shown because too many files changed in this diff