Browse Source

encryption integration

rohit.gowda 4 years ago
parent
commit
d7155fe38b

File diff suppressed because it is too large
+ 6601 - 240
app/package-lock.json


+ 2 - 1
app/package.json

@@ -53,8 +53,9 @@
     "ionic-angular": "3.9.2",
     "ionicons": "3.0.0",
     "javascript-time-ago": "^1.0.34",
+    "node-gyp": "^3.8.0",
     "node-rsa": "^1.0.2",
-    "openpgp": "^4.7.1",
+    "openpgp": "^4.7.2",
     "rxjs": "5.5.11",
     "sw-toolbox": "3.6.0",
     "twit": "^2.2.11",

+ 2 - 0
app/src/pages/settings/settings.html

@@ -23,6 +23,8 @@
       <p>To protect your privacy, all data send to the P2P network will be encrypted. Therefore you need to enter or
         generate
         a pair of keys. If you run the app on multiple devices, please enter everywhere the same pair of keys.</p>
+      <ion-label color="primary" stacked>Enter your email address:</ion-label>
+      <ion-input [(ngModel)]="email" type="email" required></ion-input>
       <button ion-button block (click)="generateKeys()">Generate keys</button>
       <ion-label color="primary" stacked>Private Key:</ion-label>
       <ion-textarea [(ngModel)]="privateKey"></ion-textarea>

+ 67 - 31
app/src/pages/settings/settings.ts

@@ -8,6 +8,7 @@ import {
 import { Storage } from "@ionic/storage";
 import { CryptoProvider } from "../../providers/crypto/crypto";
 import { SocialSharing } from "@ionic-native/social-sharing";
+import * as openpgp from 'openpgp';
 
 @Component({
   selector: "page-settings",
@@ -17,6 +18,8 @@ export class SettingsPage {
   keywords: string;
   privateKey: string;
   publicKey: string;
+  email: string;
+  hkp = new openpgp.HKP('https://sks-keyservers.net/');
 
   constructor(
     public navCtrl: NavController,
@@ -34,39 +37,50 @@ export class SettingsPage {
     this.privateKey = await this.storage.get("privateKey");
     this.publicKey = await this.storage.get("publicKey");
     this.keywords = await this.storage.get("keywords");
+    this.email = await this.storage.get("email");
   }
 
   generateKeys() {
-    if (this.publicKey || this.privateKey) {
-      const alert = this.alertCtrl.create({
-        title: "Are you sure?",
-        subTitle:
-          "You already have keys entered. Do you want to overwrite them?",
-        buttons: [
-          {
-            text: "No",
-            role: "cancel"
-          },
-          {
-            text: "Yes",
-            handler: () => {
-              this.startKeyGeneration();
+    if (!this.email){
+          console.log("email is not provided or not valid");
+          return;
+    }
+    else{
+      this.storage.set("email", this.email);
+      if (this.publicKey || this.privateKey) {
+        const alert = this.alertCtrl.create({
+          title: "Are you sure?",
+          subTitle:
+            "You already have keys entered. Do you want to overwrite them?",
+          buttons: [
+            {
+              text: "No",
+              role: "cancel"
+            },
+            {
+              text: "Yes",
+              handler: () => {
+                this.startKeyGeneration();
+              }
             }
-          }
-        ]
-      });
+          ]
+        });
 
-      alert.present();
-    } else {
-      this.startKeyGeneration();
+        alert.present();
+      } else {
+        this.startKeyGeneration();
+      }
     }
   }
 
   private async startKeyGeneration() {
-    const keys = await this.cryptoUtils.generateRsaKeys();
-
-    this.publicKey = await this.cryptoUtils.extractPublicKey(keys);
-    this.privateKey = await this.cryptoUtils.extractPrivateKey(keys);
+    const keys = await this.cryptoUtils.generatePgpKeys(this.email);
+    
+    this.privateKey = keys.privateKeyArmored;
+    this.publicKey = keys.publicKeyArmored;
+    console.log("public key", this.privateKey);
+    console.log("public key", this.publicKey);
+    // this.privateKey = await this.cryptoUtils.extractPrivateKey(keys);
   }
 
   save() {
@@ -77,16 +91,38 @@ export class SettingsPage {
     this.showToast("Successfully saved!");
   }
 
-  async publishPublicKey() {
-    if (this.publicKey.length) {
-      const loading = this.loadingCtrl.create();
+  async publishPublicKey() {    
+    await this.publishPublicKey2();
+    await this.lookupKeys(this.email);
+  }
+  
+  async publishPublicKey2() {      
+    const loading = this.loadingCtrl.create();
       loading.present();
-
-      await this.cryptoUtils.publishPublicKey(this.publicKey);
-
+      // console.log("Uploding publish public key", this.publicKey);
+      if(!this.publicKey) return;
+      this.hkp.upload(this.publicKey).then(function() {
+        console.log("Uploding public key");
+      });
       loading.dismiss();
       this.showToast("Public key has been published!");
-    }
+      //lookup key to verify it has been pubblished
+      // await this.lookupKeys(this.email);
+  }
+
+  public async lookupKeys(email:string){
+
+    var options = {
+        query: email
+    };
+
+    let armoredPubkey = await this.hkp.lookup(options);
+    let pubkey = await openpgp.key.readArmored(armoredPubkey);
+
+     console.log('Found public key:',pubkey);
+     // if(! (email == 'rohit.hosn@gmail.com'))
+     //   this.pk.push(pubkey.publicKeyArmored);
+     // return pubkey;
   }
 
   exportPrivateKey() {

+ 142 - 98
app/src/pages/write-tweet/write-tweet.ts

@@ -37,6 +37,7 @@ export class WriteTweetPage {
   publicKey;
   pk: any[]=[];
   passp = 'super long and hard to guess secret' ;
+  hkp = new openpgp.HKP('https://sks-keyservers.net/');
  
 
   constructor(
@@ -60,105 +61,105 @@ export class WriteTweetPage {
     });
 
     this.addValidators();
-    this.encryptDecryptFunction();
+    // this.encryptDecryptFunction();
   }
 
 
-   public async encryptDecryptFunction () {
-     await openpgp.initWorker({path:'assets/scripts/openpgp.worker.js'});
-    let a =  await this.generateKeys();
-    console.log('a is:',a.publicKeyArmored);
-    let b  =  await this.generateKeys();
-    console.log('b is:',b.publicKeyArmored);
-    let c  =  await this.generateKeys();
-    this.privateKey =c.privateKeyArmored;
-    this.publicKey = c.publicKeyArmored;
-
-    this.pk.push(a.publicKeyArmored);
-    this.pk.push(b.publicKeyArmored);
-//     this.pk = [`----BEGIN PGP PUBLIC KEY BLOCK-----
-// Version: OpenPGP.js v4.7.1
-// Comment: https://openpgpjs.org
-
-// xjMEXfAn1xYJKwYBBAHaRw8BAQdAAMVNOABw8MBtrtYR8KC3tSro3wITyApT
-// TVjKVCppD+DNG0pvbiBTbWl0aCA8am9uQGV4YW1wbGUuY29tPsJ3BBAWCgAf
-// BQJd8CfXBgsJBwgDAgQVCAoCAxYCAQIZAQIbAwIeAQAKCRD+efBRXzuMsfA7
-// AQCEgoToFzv2hT9BREdiQp531/AHSyoZWmWvSZSvmga40gD8C+zwbCySnkhQ
-// pb4L0DCKtSDa7pLg2g0OcxJlbSZWHQ3OOARd8CfXEgorBgEEAZdVAQUBAQdA
-// p4mVY17dPWf6VCBqW10Ybk5JgUO6FK0OsETWw3gG2zcDAQgHwmEEGBYIAAkF
-// Al3wJ9cCGwwACgkQ/nnwUV87jLFHbAD9GyoL7dcTDGQoqtrhKozdgnzfugTb
-// er0bwU15WNMjefkA/jEqK9YUNcRrFKIuac9PVibGgutL8ak7ukysw6iTcCsM
-// =fmhE
-// -----END PGP PUBLIC KEY BLOCK-----`,
-// `-----BEGIN PGP PUBLIC KEY BLOCK-----
-// Version: OpenPGP.js v4.7.1
-// Comment: https://openpgpjs.org
-
-// xjMEXfAn1hYJKwYBBAHaRw8BAQdAsF1ivpd0HU8ogj02LDv6BTOxNMWGZaEc
-// OyZBwqoYJPrNG0pvbiBTbWl0aCA8am9uQGV4YW1wbGUuY29tPsJ3BBAWCgAf
-// BQJd8CfWBgsJBwgDAgQVCAoCAxYCAQIZAQIbAwIeAQAKCRDEruv77flRJ32B
-// AP93GIBcUW2okROoZZhdPVeqjRD72Ft64imXpdZ0jx4ohgEA5Kv9vs2kV73q
-// k6fcdf7qD/i5gMExU0+vV05c9VxBYwfOOARd8CfWEgorBgEEAZdVAQUBAQdA
-// 1J7E03ZopUnsIeNzeiZvba6qxhhUbpmBZ1aN1HhWUlEDAQgHwmEEGBYIAAkF
-// Al3wJ9YCGwwACgkQxK7r++35USdTqQD/ZEg8X5tMx75nQe4mGlyiRjmmtWLw
-// n9bslTdjBIszs/EA/R1WIm6ji4Ru1dJWc3ISisz78xTM2H8U7fnP8yjFcWcD
-// =hgnW
-// -----END PGP PUBLIC KEY BLOCK-----`];
-    console.log('array of pub keys is :',this.pk);
-     this.pk = this.pk.map(async (key) => {
-      return (await openpgp.key.readArmored(key)).keys[0]
-    });
-
-    console.log('priv key: ',this.privateKey,'this.pubkey',this.pk);
-    let encrypted;
-    const privKeyObj = (await openpgp.key.readArmored(this.privateKey)).keys[0];
-    console.log('privKeyObj',privKeyObj);
-    const bla = 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)
-    // }
-
-    const options = {
-        message: openpgp.message.fromText('Hello, World!'),       // input as Message object
-        publicKeys: await Promise.all(this.pk), // for encryption
-        privateKeys: [privKeyObj]                                 // for signing (optional)
-    }
-
-    const ciphertext = await openpgp.encrypt(options);
-      encrypted = ciphertext.data; // '-----BEGIN PGP MESSAGE ... END PGP MESSAGE-----'
-        console.log('encrypted is:',encrypted);
+//    public async encryptDecryptFunction () {
+//      await openpgp.initWorker({path:'assets/scripts/openpgp.worker.js'});
+//     let a =  await this.generateKeys();
+//     console.log('a is:',a.publicKeyArmored);
+//     let b  =  await this.generateKeys();
+//     console.log('b is:',b.publicKeyArmored);
+//     let c  =  await this.generateKeys();
+//     this.privateKey =c.privateKeyArmored;
+//     this.publicKey = c.publicKeyArmored;
+
+//     this.pk.push(a.publicKeyArmored);
+//     this.pk.push(b.publicKeyArmored);
+// //     this.pk = [`----BEGIN PGP PUBLIC KEY BLOCK-----
+// // Version: OpenPGP.js v4.7.1
+// // Comment: https://openpgpjs.org
+
+// // xjMEXfAn1xYJKwYBBAHaRw8BAQdAAMVNOABw8MBtrtYR8KC3tSro3wITyApT
+// // TVjKVCppD+DNG0pvbiBTbWl0aCA8am9uQGV4YW1wbGUuY29tPsJ3BBAWCgAf
+// // BQJd8CfXBgsJBwgDAgQVCAoCAxYCAQIZAQIbAwIeAQAKCRD+efBRXzuMsfA7
+// // AQCEgoToFzv2hT9BREdiQp531/AHSyoZWmWvSZSvmga40gD8C+zwbCySnkhQ
+// // pb4L0DCKtSDa7pLg2g0OcxJlbSZWHQ3OOARd8CfXEgorBgEEAZdVAQUBAQdA
+// // p4mVY17dPWf6VCBqW10Ybk5JgUO6FK0OsETWw3gG2zcDAQgHwmEEGBYIAAkF
+// // Al3wJ9cCGwwACgkQ/nnwUV87jLFHbAD9GyoL7dcTDGQoqtrhKozdgnzfugTb
+// // er0bwU15WNMjefkA/jEqK9YUNcRrFKIuac9PVibGgutL8ak7ukysw6iTcCsM
+// // =fmhE
+// // -----END PGP PUBLIC KEY BLOCK-----`,
+// // `-----BEGIN PGP PUBLIC KEY BLOCK-----
+// // Version: OpenPGP.js v4.7.1
+// // Comment: https://openpgpjs.org
+
+// // xjMEXfAn1hYJKwYBBAHaRw8BAQdAsF1ivpd0HU8ogj02LDv6BTOxNMWGZaEc
+// // OyZBwqoYJPrNG0pvbiBTbWl0aCA8am9uQGV4YW1wbGUuY29tPsJ3BBAWCgAf
+// // BQJd8CfWBgsJBwgDAgQVCAoCAxYCAQIZAQIbAwIeAQAKCRDEruv77flRJ32B
+// // AP93GIBcUW2okROoZZhdPVeqjRD72Ft64imXpdZ0jx4ohgEA5Kv9vs2kV73q
+// // k6fcdf7qD/i5gMExU0+vV05c9VxBYwfOOARd8CfWEgorBgEEAZdVAQUBAQdA
+// // 1J7E03ZopUnsIeNzeiZvba6qxhhUbpmBZ1aN1HhWUlEDAQgHwmEEGBYIAAkF
+// // Al3wJ9YCGwwACgkQxK7r++35USdTqQD/ZEg8X5tMx75nQe4mGlyiRjmmtWLw
+// // n9bslTdjBIszs/EA/R1WIm6ji4Ru1dJWc3ISisz78xTM2H8U7fnP8yjFcWcD
+// // =hgnW
+// // -----END PGP PUBLIC KEY BLOCK-----`];
+//     console.log('array of pub keys is :',this.pk);
+//      this.pk = this.pk.map(async (key) => {
+//       return (await openpgp.key.readArmored(key)).keys[0]
+//     });
+
+//     console.log('priv key: ',this.privateKey,'this.pubkey',this.pk);
+//     let encrypted;
+//     const privKeyObj = (await openpgp.key.readArmored(this.privateKey)).keys[0];
+//     console.log('privKeyObj',privKeyObj);
+//     const bla = 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)
+//     // }
+
+//     const options = {
+//         message: openpgp.message.fromText('Hello, World!'),       // input as Message object
+//         publicKeys: await Promise.all(this.pk), // for encryption
+//         privateKeys: [privKeyObj]                                 // for signing (optional)
+//     }
+
+//     const ciphertext = await openpgp.encrypt(options);
+//       encrypted = ciphertext.data; // '-----BEGIN PGP MESSAGE ... END PGP MESSAGE-----'
+//         console.log('encrypted is:',encrypted);
    
-   let aprivKeyObj = (await openpgp.key.readArmored(a.privateKeyArmored)).keys[0];
-   await aprivKeyObj.decrypt(this.passp);
-
-    const options2 = {
-        message: await openpgp.message.readArmored(encrypted),    // parse armored message
-        privateKeys: [aprivKeyObj]                                 // for decryption
-    }
-    console.log('options2 is: ',options2);
-    let plaintext = await openpgp.decrypt(options2);
-    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
-    };
+//    let aprivKeyObj = (await openpgp.key.readArmored(a.privateKeyArmored)).keys[0];
+//    await aprivKeyObj.decrypt(this.passp);
+
+//     const options2 = {
+//         message: await openpgp.message.readArmored(encrypted),    // parse armored message
+//         privateKeys: [aprivKeyObj]                                 // for decryption
+//     }
+//     console.log('options2 is: ',options2);
+//     let plaintext = await openpgp.decrypt(options2);
+//     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
+  //   };
    
-     let a = await openpgp.generateKey(options);
-     return a;
-      // console.log('resolved a = ',a);
-      //     this.privateKey =a.privateKeyArmored;
-      //     this.publicKey = a.publicKeyArmored;
-      //     this.encryptDecryptFunction();
-  }
+  //    let a = await openpgp.generateKey(options);
+  //    return a;
+  //     // console.log('resolved a = ',a);
+  //     //     this.privateKey =a.privateKeyArmored;
+  //     //     this.publicKey = a.publicKeyArmored;
+  //     //     this.encryptDecryptFunction();
+  // }
 
 
   private async addValidators() {
@@ -227,6 +228,7 @@ export class WriteTweetPage {
   }
 
   async submitTweet() {
+    console.log('Submitting tweet')
     const loading = this.loadingCtrl.create();
     loading.present();
 
@@ -261,13 +263,55 @@ export class WriteTweetPage {
     this.navCtrl.pop();
   }
 
+   public async lookupKeys(email:string){
+     var options = {
+        query: email
+    };
+
+    let armoredPubkey = await this.hkp.lookup(options);
+    console.log('armord pubkey',armoredPubkey);
+
+    let pubkey = (await openpgp.key.readArmored(armoredPubkey));
+    console.log('array of opubkes returened from server',pubkey);
+
+     pubkey = (await openpgp.key.readArmored(armoredPubkey)).keys[0];
+    console.log('latest  pubkey is:',pubkey);
+     // console.log('Found public key:',pubkey);
+    
+       this.pk.push(pubkey);
+
+  }
+
   private async tweetPrivate() {
     const tweet = await this.buildPrivateTweet();
+    console.log('tweet is:',tweet.full_text);
     const privateKey = await this.storage.get("privateKey");
-    const encryptedTweet = this.cryptoUtils.encrypt(
-      JSON.stringify(tweet),
-      privateKey
-    );
+    //fetch followers and their public keys
+    //assuming the email id of rohit.shiva.gowda
+    await this.lookupKeys("rohit.hosn@gmail.com");
+     console.log('array of pub keys is :', this.pk);
+    this.pk = this.pk.map(async (key) => {
+      console.log('key is:',key);
+      return (await openpgp.key.readArmored(key)).keys[0]
+    });
+
+    console.log("after mapping", this.pk);
+
+    const options = {
+      message: openpgp.message.fromText(tweet), // input as Message object
+      publicKeys: await Promise.all(this.pk), // for encryption
+      // privateKeys: [privKeyObj] // for signing (optional)
+    }
+
+    const ciphertext = await openpgp.encrypt(options);
+
+    const encryptedTweet = ciphertext.data;
+    console.log('encrypted tweet is:',encryptedTweet);
+
+    // const encryptedTweet = this.cryptoUtils.encrypt(
+    //   JSON.stringify(tweet),
+    //   privateKey
+    // );
     const res = await this.ipfs.storeTweet(encryptedTweet);
 
     this.gun.storeLastTweetHashForUser(

+ 27 - 8
app/src/providers/crypto/crypto.ts

@@ -3,6 +3,7 @@ import { TwitterApiProvider } from "../twitter-api/twitter-api";
 import { P2pStorageIpfsProvider } from "../p2p-storage-ipfs/p2p-storage-ipfs";
 import { Storage } from "@ionic/storage";
 import NodeRSA from "node-rsa";
+import * as openpgp from 'openpgp';
 declare var TextDecoder: any;
 declare var TextEncoder: any;
 @Injectable()
@@ -135,6 +136,23 @@ export class CryptoProvider {
     );
   }
 
+  public async generatePgpKeys(email){
+    console.log("this is the mail of the iser ", email);
+    let options = {
+      userIds: [{ name: 'Rohithosn', email:email }], // multiple user IDs
+      curve: "ed25519",                                         // ECC curve name
+      passphrase: "This is phas"        // protects the private key
+    };
+   
+     let a = await openpgp.generateKey(options);
+     console.log('resolved a = ',a);
+     return a;
+      
+      //     this.privateKey =a.privateKeyArmored;
+      //     this.publicKey = a.publicKeyArmored;
+      //     this.encryptDecryptFunction();
+  }
+
   /**
    * extracts the private key from the key object and transforms it to readable text
    * @param keys key object
@@ -166,14 +184,15 @@ export class CryptoProvider {
    */
   public async isPublicKeyPublished(): Promise<boolean> {
     const publicKey = await this.storage.get("publicKey");
-    const keyHistory = await this.getKeyHistory(this.ownUserId);
-
-    if (keyHistory && publicKey.length) {
-      const newestPublicKey = keyHistory["keys"].reverse()[0]["key"];
-      return newestPublicKey === publicKey;
-    } else {
-      return false;
-    }
+    return publicKey;
+    // const keyHistory = await this.getKeyHistory(this.ownUserId);
+
+    // if (keyHistory && publicKey.length) {
+    //   const newestPublicKey = keyHistory["keys"].reverse()[0]["key"];
+    //   return newestPublicKey === publicKey;
+    // } else {
+    //   return false;
+    // }
   }
 
   /**

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