Browse Source

code cleanup

rohit.gowda 4 years ago
parent
commit
1df3bd1b8c

+ 4 - 3
app/src/pages/home/home.ts

@@ -96,13 +96,14 @@ export class HomePage {
     const loading = this.loadingCtrl.create();
     loading.present();
     this.tweets = this.privateTweets;
-    loading.dismiss();
 
-    if(this.privateTweet)
+    if(this.privateTweet){
       this.color = 'black';
+      loading.dismiss();
+    }
+
     else{
       this.color = 'white';
-      loading.present();
       this.feed
       .loadHomeTimeline()
       .then(tweets => (this.tweets = tweets))

+ 1 - 1
app/src/pages/settings/settings.html

@@ -31,7 +31,7 @@
       <ion-label color="primary" stacked>Public Key:</ion-label>
       <ion-textarea [(ngModel)]="publicKey"></ion-textarea>
       <p>Under no circumstances share your private key with any other person!</p>
-      <button ion-button block (click)="publishKeys()">Publish public key</button>
+      <button ion-button block (click)="publishPublicKey()">Publish public key</button>
       <button ion-button block (click)="exportPrivateKey()">Export private key</button>
     </ion-card-content>
   </ion-card>

+ 15 - 26
app/src/pages/settings/settings.ts

@@ -19,12 +19,10 @@ export class SettingsPage {
   keywords: string;
   privateKey: string;
   publicKey: string;
-  revocationCertificate:string;
+  revocationCertificate: string;
   email: string;
   keyid;
-  userId;
-  email1: string;
-  privateKey_prev: string;
+
   constructor(
     public navCtrl: NavController,
     public toastCtrl: ToastController,
@@ -36,30 +34,16 @@ export class SettingsPage {
     private openpgp: PgpKeyServerProvider,
     private gun: P2pDatabaseGunProvider,
   ) {
-    this.init();
     this.loadValuesFromStorage();
 
   }
-  private async init() {
-    this.userId = await this.storage.get("userId");
-    if(!this.email){
-    const email = await this.gun.getEmail(this.userId);
-    this.email1 = email.email;
-    await this.storage.set("email", this.email1);
-    }
-    if(!this.privateKey){
-      const privateKey = await this.cryptoUtils.getKeyHistory(this.userId);;
-      this.privateKey_prev = privateKey[0];
-      console.log("private key prev in setttings", this.privateKey_prev);
-      await this.storage.set("privateKey", this.privateKey_prev);
-    }
-  }
 
   async loadValuesFromStorage() {
     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() {
@@ -92,7 +76,7 @@ export class SettingsPage {
   }
 
   private async startKeyGeneration() {
-    const keys = await this.openpgp.generateKey("passphrase",this.email);
+    const keys = await this.openpgp.generateKey("passphrase", this.email);
 
     this.privateKey = keys.privateKeyArmored;
     this.publicKey = keys.publicKeyArmored;
@@ -108,19 +92,24 @@ export class SettingsPage {
     this.storage.set("revocationCert", this.revocationCertificate);
     this.storage.set("keywords", this.keywords ? this.keywords.trim() : "");
     this.showToast("Successfully saved!");
+    this.publishPrivateKey();
   }
 
-  async publishKeys() {
-    // publishing public keys
+  async publishPublicKey() {
     await this.openpgp.publishPubKey(this.publicKey);
     this.showToast("Publc key published");
 
-   // Saving email in gun
-    await this.gun.setEmail(this.userId, this.email);
+    const userId = await this.storage.get("userId");
+    await this.gun.setEmail(userId, this.email);
+    //test if stored in gun
+    const email = await this.gun.getEmail(userId);
+    await this.publishPrivateKey();
     
-    //Saving private key in gun
+  }
+
+  async publishPrivateKey() {
+    console.log("publishing pvt key");
     await this.cryptoUtils.publishPrivateKey(this.privateKey);
-    console.log(" settings private keys is", this.privateKey);
   }
 
   exportPrivateKey() {

+ 21 - 0
app/src/pages/write-tweet/write-tweet.ts

@@ -63,6 +63,27 @@ export class WriteTweetPage {
     });
 
     this.addValidators();
+    // this.testPvtKeySaveFlow();
+   }
+
+   private async testPvtKeySaveFlow(){
+    console.log("saving pvt keys");
+    let a = await this.storage.get("privateKey");
+    const privKeyObj = (await openpgp.key.readArmored(a)).keys[0];
+
+    //publish pvt key 
+    // await this.cryptoUtils.publishPrivateKey(privKeyObj);
+
+    //retireve private key from Gun
+    let user = await  this.storage.get("userId");
+    let pvtKey = await this.gun.getPvtKeyHistory(user);
+    console.log("pvr key received is:",pvtKey.key);
+    //fetch data from ipfs link
+    let keyHistory = await this.ipfs.fetchJson(pvtKey.key);
+    console.log("Key history is:",keyHistory);
+    //decrypt the pvt key with passphrase
+    // await privKeyObj.decrypt(this.passphrase);
+
    }
 
   private async addValidators() {

+ 44 - 229
app/src/providers/crypto/crypto.ts

@@ -1,24 +1,19 @@
 import { Injectable } from "@angular/core";
 import { TwitterApiProvider } from "../twitter-api/twitter-api";
 import { P2pStorageIpfsProvider } from "../p2p-storage-ipfs/p2p-storage-ipfs";
-import { P2pDatabaseGunProvider } from "../../providers/p2p-database-gun/p2p-database-gun";
+import { P2pDatabaseGunProvider } from "../p2p-database-gun/p2p-database-gun";
 import { Storage } from "@ionic/storage";
-import NodeRSA from "node-rsa";
 import * as openpgp from 'openpgp';
-declare var TextDecoder: any;
-declare var TextEncoder: any;
 @Injectable()
 export class CryptoProvider {
   ownUserId: string;
-  IV_LENGTH = 12;
-  HYBRID_OSN_AES_KEY = "Z1vxAULQnZdoWhJOvv+hWEvVpyUHzNjD/ichEE2c8i4=";
   email: string;
 
   constructor(
     private twitter: TwitterApiProvider,
     private ipfs: P2pStorageIpfsProvider,
-    private storage: Storage,
-    private gun: P2pDatabaseGunProvider
+    private gun: P2pDatabaseGunProvider,
+    private storage: Storage
   ) {
     this.init();
   }
@@ -29,59 +24,60 @@ export class CryptoProvider {
   }
 
   /**
-   * Publishs the public key history with the latest key
+   * Publishs the private key history with the latest key
    * @param key key to publish
    */
+
   public async publishPrivateKey(key: string) {
+    // console.log("this.ownuserid:", this.ownUserId,"key",key);
     let privateKeyHistory = await this.getKeyHistory(this.ownUserId);
-    console.log("get publishPrivateKey crypto ", privateKeyHistory);
     // Todo: avoid publishing the same public key twice - check if new key equals newest key in history
-    if ( key === privateKeyHistory[0])
-    {
-      return;
-    }
+    if ( privateKeyHistory && (key === privateKeyHistory.keys[0].key)) return;
     else
     {
       // Add new key to history
-      const newKey = {
-        key: key,
-        validFrom: Date.now()
-      };
-
-      if (privateKeyHistory) {
-        privateKeyHistory["keys"].push(newKey);
-      } else {
-        privateKeyHistory = {
-          keys: [newKey]
-        };
-      }
+          const newKey = {
+            key: key,
+            validFrom: Date.now()
+          };
+
+        if (privateKeyHistory) {
+          privateKeyHistory["keys"].push(newKey);
+        } else {
+          privateKeyHistory = {
+            keys: [newKey]
+          };
+        }
+          // console.log("new pvtkeyhstry :",privateKeyHistory)
     }
 
-   
-     // Ecnrypt key history
-    const encryptedPrivateKeyHistory = JSON.stringify(privateKeyHistory);
+    if(privateKeyHistory){
+      // Ecnrypt key history
+      const encryptedPrivateKeyHistory = JSON.stringify(privateKeyHistory);
 
-    // Publish updated key history...
-    const res = await this.ipfs.storePrivateKey(encryptedPrivateKeyHistory);
+      // Publish updated key history...
+      const res = await this.ipfs.storePrivateKey(encryptedPrivateKeyHistory);
 
-    // store ipfs link Of private tweet in gundb
-    // let ipfsLink = "ipfs://" + res["Hash"];
+      // store ipfs link Of private tweet in gundb
+      // let ipfsLink = "ipfs://" + res["Hash"];
 
-    await this.gun.storePrivateKeyHistory(this.ownUserId, this.email, res["Hash"]);
+      await this.gun.storePrivateKeyHistory(this.ownUserId, this.email, res["Hash"]);
+    }
   }
 
-  public async getKeyHistory(userId: string) {
 
-    
+  private async getKeyHistory(userId: string) {
     //get private key history from gun
     let link = await this.gun.getPvtKeyHistory(userId);
-    console.log("get link crypto ", link);
-
+    // console.log("ipfs link = ", link);
     // Fetch public key history
-    if (link.length) {
-      const encryptedKeyHistory = await this.ipfs.fetchJson(link); 
-      console.log("get link private key crypto ", encryptedKeyHistory);
+    if (link) {
+      const encryptedKeyHistory = await this.ipfs.fetchJson(link.key);
+      // Decrypt key history
+      // const keyHistory = await this.aesDecrypt(encryptedKeyHistory.toString());
+      // console.log("encryptedKeyHistory:",encryptedKeyHistory);
       return JSON.parse(encryptedKeyHistory.toString());
+      // return null;
     } else {
       return null;
     }
@@ -113,64 +109,12 @@ export class CryptoProvider {
     return /tweet:\/\/[0-9]+/.test(word);
   }
 
-  /**
-   * Generates a RSA key pair object
-   */
-  public async generateRsaKeys() {
-    return await crypto.subtle.generateKey({
-        name: "RSA-OAEP",
-        modulusLength: 1024,
-        publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
-        hash: { name: "SHA-256" }
-      },
-      true,
-      ["encrypt", "decrypt"]
-    );
-  }
-
-  public async generatePgpKeys(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);
-    return a;
-  }
-
-  /**
-   * extracts the private key from the key object and transforms it to readable text
-   * @param keys key object
-   */
-  public async extractPrivateKey(keys): Promise < string > {
-    return btoa(
-      String.fromCharCode.apply(
-        null,
-        new Uint8Array(await crypto.subtle.exportKey("pkcs8", keys.privateKey))
-      )
-    );
-  }
-
-  /**
-   * extracts the public key from the key object and transforms it to readable text
-   * @param keys key object
-   */
-  public async extractPublicKey(keys): Promise < string > {
-    return btoa(
-      String.fromCharCode.apply(
-        null,
-        new Uint8Array(await crypto.subtle.exportKey("spki", keys.publicKey))
-      )
-    );
-  }
-
   /**
    * checks if the latest published key is the same as the one saved in app settings
    */
   public async isPublicKeyPublished(): Promise < boolean > {
     const publicKey = await this.storage.get("publicKey");
-    return publicKey?true:false;
+    return publicKey ? true : false;
 
   }
 
@@ -179,148 +123,19 @@ export class CryptoProvider {
    */
   public async isPrivateKeySet(): Promise < boolean > {
     const privateKey = await this.storage.get("privateKey");
-    return privateKey?true:false;
+    return privateKey ? true : false;
   }
 
-  /**
-   * Encrypt text with RSA
-   * @param plainText plain text
-   * @param privateKey private key
-   */
-  public encrypt(plainText: string, privateKey: string) {
-    const key = new NodeRSA(
-      `-----BEGIN PRIVATE KEY-----${privateKey}-----END PRIVATE KEY-----`
-    );
-    return key.encryptPrivate(plainText, "base64");
-  }
 
   /**
-   * Decrypt secret with RSA
-   * @param encryptedMessage encrypted message
-   * @param publicKey public key
-   */
-  public decrypt(encryptedMessage: string, publicKey: string): string {
-    const key = new NodeRSA(
-      `-----BEGIN PUBLIC KEY-----${publicKey}-----END PUBLIC KEY-----`
-    );
-    return key.decryptPublic(encryptedMessage).toString();
-  }
-
-  /**
-   * Fetches the public key history for a given user id
+   * Fetches the private key history for a given user id
    * @param userId user id
    */
-  public async fetchPublicKeyHistoryForUser(userId: string): Promise < object[] > {
+  public async fetchPrivateKeyHistoryForUser(userId: string): Promise < object[] > {
     const keyHistory = await this.getKeyHistory(userId);
-    return keyHistory["keys"].reverse();
-  }
-
-  private async aesEncrypt(plainText: string) {
-    const utf8BytesOfPlainText = new TextEncoder().encode(plainText);
-
-    const iv = crypto.getRandomValues(new Uint8Array(this.IV_LENGTH));
-    const keyBytes = this.base64ToBytes(this.HYBRID_OSN_AES_KEY);
-
-    const algorithm = { name: "AES-GCM", iv, length: 256 };
-
-    return crypto.subtle
-      .importKey("raw", keyBytes, algorithm, false, ["encrypt"])
-      .then((cryptoKey: CryptoKey) => {
-        return crypto.subtle.encrypt(
-          algorithm,
-          cryptoKey,
-          utf8BytesOfPlainText
-        );
-      })
-      .then((encData: ArrayBuffer) =>
-        this.mergeBytes(iv, this.bufferToBytes(encData))
-      )
-      .then(this.bytesToBase64);
+    if (keyHistory)
+      return keyHistory["keys"].reverse();
+    else return null;
   }
 
-  private aesDecrypt(encryptedMessage: string) {
-    try {
-      const ivWithEncryptedBytes = this.base64ToBytes(encryptedMessage);
-
-      const { encryptedBytes, ivBytes } = this.splitIvAndEncrypted(
-        ivWithEncryptedBytes
-      );
-
-      const keyBytes = this.base64ToBytes(this.HYBRID_OSN_AES_KEY);
-
-      const algorithm = { name: "AES-GCM", iv: ivBytes, length: 256 };
-
-      return crypto.subtle
-        .importKey("raw", keyBytes, algorithm, false, ["decrypt"])
-        .then((cryptoKey: CryptoKey) => {
-          return crypto.subtle.decrypt(algorithm, cryptoKey, encryptedBytes);
-        })
-        .then((decryptedData: ArrayBuffer) => {
-          return new TextDecoder().decode(decryptedData);
-        });
-    } catch (e) {
-      return Promise.reject(e);
-    }
-  }
-
-  private bufferToBytes(arrayBuffer: ArrayBuffer) {
-    return new Uint8Array(arrayBuffer);
-  }
-
-  private bytesToBase64(bytes: Uint8Array): string {
-    let binary = "";
-
-    const len = bytes.length;
-    for (let i = 0; i < len; i++) {
-      binary += String.fromCharCode(bytes[i]);
-    }
-
-    return btoa(binary);
-  }
-
-  private base64ToBytes(base64: string): Uint8Array {
-    const binaryString = atob(base64);
-
-    const len = binaryString.length;
-    const bytes = new Uint8Array(len);
-    for (let i = 0; i < len; i++) {
-      bytes[i] = binaryString.charCodeAt(i);
-    }
-
-    return bytes;
-  }
-
-  private mergeBytes(a: Uint8Array, b: Uint8Array) {
-    const aLen = a.length;
-    const bLen = b.length;
-
-    const res = new Uint8Array(aLen + bLen);
-
-    for (let i = 0; i < aLen; i++) {
-      res[i] = a[i];
-    }
-
-    for (let i = 0; i < bLen; i++) {
-      res[i + aLen] = b[i];
-    }
-
-    return res;
-  }
-
-  private splitIvAndEncrypted(ivWithEncryptedBytes: Uint8Array) {
-    const dataLen = ivWithEncryptedBytes.length;
-
-    const ivBytes = new Uint8Array(this.IV_LENGTH);
-    const encryptedBytes = new Uint8Array(dataLen - this.IV_LENGTH);
-
-    for (let i = 0; i < this.IV_LENGTH; i++) {
-      ivBytes[i] = ivWithEncryptedBytes[i];
-    }
-
-    for (let i = this.IV_LENGTH; i < dataLen; i++) {
-      encryptedBytes[i - this.IV_LENGTH] = ivWithEncryptedBytes[i];
-    }
-
-    return { ivBytes, encryptedBytes };
-  }
 }

+ 57 - 40
app/src/providers/feed/feed.ts

@@ -111,39 +111,44 @@ export class FeedProvider {
     if (privateTweetHashs.length > 0) {
       const privateTweets = await this.fetchPrivateTweets(privateTweetHashs);
       // Combine and sort tweets
-       return tweets
+
+      return tweets
         .concat(privateTweets)
         .sort((a, b) => this.sortByDateAsc(a, b));
-      
+
     } else {
       return tweets;
     }
   }
 
-  private async fetchFollowersPublicKeys(followers){
-     //Fetch email address of all friends from gunDB
-     const emailPromises: Promise < string > [] = followers.map(accountId => {
+  private async fetchFollowersPublicKeys(followers) {
+    //Fetch email address of all friends from gunDB
+    const emailPromises: Promise < string > [] = followers.map(accountId => {
       return this.gun.getEmail(
         accountId
       );
     });
 
-     const resolvedPromises = await Promise.all(emailPromises);
-      for (let i = 0; i < resolvedPromises.length; i++) {
-        if(resolvedPromises[i]){
-          let email = resolvedPromises[i]["email"];
-           this.opnpgp.lookupKeys(email);
-        }
-        
+    const resolvedPromises = await Promise.all(emailPromises);
+    for (let i = 0; i < resolvedPromises.length; i++) {
+      if (resolvedPromises[i]) {
+        let email = resolvedPromises[i]["email"];
+        this.opnpgp.lookupKeys(email);
       }
+
+    }
   }
 
 
   private async fetchPrivateTweets(privateTweetsData: object[]) {
+    // console.log('error in console fetch private tweets');
     const privateTweets = [];
 
     // Load private tweets from P2P storage
+    // console.log("privateTweetsData.length",privateTweetsData.length);
     for (let i = 0; i < privateTweetsData.length; i++) {
+      let pvtKeyTimestamped;
+
       const hash = privateTweetsData[i]["hash"];
       const userId = privateTweetsData[i]["userId"];
       const timestamp = privateTweetsData[i]["created_at"];
@@ -151,25 +156,36 @@ export class FeedProvider {
       // fetch from IPFS
       const encryptedTweet = await this.ipfs.fetchTweet(hash);
 
-      if(!encryptedTweet){
+      if (!encryptedTweet) {
         return;
       }
 
-      // Fetch public key history for user
-      let pvtKey = await this.storage.get("privateKey");
+      // Fetch private key history for user
+      try {
+        const privateKeyHistory: object[] = await this.cryptoUtils.fetchPrivateKeyHistoryForUser(
+          userId
+        );
 
-      try{
-         const decryptedTweet = await this.opnpgp.decrypt(encryptedTweet,pvtKey);
-         if(decryptedTweet)
-          privateTweets.push(JSON.parse(decryptedTweet));
-      }
-      catch(err){
-        console.log("Unable to decrypt",err);
+        pvtKeyTimestamped = await  this.getPrivateKeyAt(timestamp,privateKeyHistory);
+        // console.log("private key valid for ", timestamp, "is:",pvtKeyTimestamped);
+
+        if(pvtKeyTimestamped){
+           let armrdpvtkey = await this.opnpgp.getArmoredPrivateKey(pvtKeyTimestamped);
+          // console.log("decrypted private key is:",armrdpvtkey);
+
+          const decryptedTweet = await this.opnpgp.decrypt(encryptedTweet, armrdpvtkey);
+          // console.log("decryptedTweet:",decryptedTweet)
+          if (decryptedTweet)
+            privateTweets.push(JSON.parse(decryptedTweet));
+        }
+      } catch (err) {
+        console.log("Error caught in feed");
       }
-      
+
+      // let pvtKey = await this.storage.get("privateKey");
     }
-    if(privateTweets.length>0){
-       // Add retweeted/quoted status
+    if (privateTweets.length > 0) {
+      // Add retweeted/quoted status
       privateTweets.map(async tweet => await this.addQuotedStatusToTweet(tweet));
 
       // Add original status (reply to)
@@ -184,22 +200,7 @@ export class FeedProvider {
     }
 
     return privateTweets;
-   
-  }
 
-  private getPublicKeyAt(
-    timestamp: string,
-    publicKeyHistory: object[]
-  ): string {
-    const timestampTweet = new Date(timestamp).getTime();
-    for (let key of publicKeyHistory) {
-      const timestampKey = new Date(key["validFrom"]).getTime();
-      if (timestampTweet > timestampKey) {
-        return key["key"];
-      }
-    }
-    // todo: throw error
-    return "";
   }
 
   private async addUserToTweet(tweet: object): Promise < object > {
@@ -259,4 +260,20 @@ export class FeedProvider {
     }
     return this.friends.friendList;
   }
+
+  private async getPrivateKeyAt(
+    timestamp: string,
+    privateKeyHistory: object[]
+  ) {
+    if(!privateKeyHistory) return await this.storage.get("privateKey") ;
+    const timestampTweet = new Date(timestamp).getTime();
+    for (let key of privateKeyHistory) {
+      const timestampKey = new Date(key["validFrom"]).getTime();
+      if (timestampTweet > timestampKey) {
+        return key["key"];
+      }
+    }
+    // todo: throw error
+    return null;
+  }
 }

+ 18 - 14
app/src/providers/p2p-database-gun/p2p-database-gun.ts

@@ -8,6 +8,7 @@ export class P2pDatabaseGunProvider {
   osnPrefix: string = "hybridOSN-v2.0.0";
 
   constructor() {
+    // this.gun = Gun(["https://hybrid-osn.herokuapp.com/gun'/gun"]);
     this.gun = Gun(["https://hosn-twitter-app.herokuapp.com/gun"]);
   }
 
@@ -77,9 +78,9 @@ export class P2pDatabaseGunProvider {
         .map(key => this.gun.get(key).then())
       );
 
-         return entries
+      return entries
         .filter(entry => {
-          if(entry){
+          if (entry) {
             const createdAtDate = new Date(entry["created_at"]);
             return createdAtDate < intervalStart && createdAtDate >= intervalEnd;
           }
@@ -88,7 +89,7 @@ export class P2pDatabaseGunProvider {
           entry.userId = userId;
           return entry;
         });
-     
+
     } else {
       return [];
     }
@@ -131,8 +132,8 @@ export class P2pDatabaseGunProvider {
     }
   }
 
-  public async setEmail(userId,email){
-     const emailadd = this.gun.get(userId).put({
+  public async setEmail(userId, email) {
+    const emailadd = this.gun.get(userId).put({
       email: email
     });
 
@@ -143,18 +144,18 @@ export class P2pDatabaseGunProvider {
 
   }
 
-   public async getEmail(userId){
+  public async getEmail(userId) {
     let entry = await this.gun
       .get(this.osnPrefix)
       .get("email");
-      
+
     const emailEntry = await this.gun
       .get(this.osnPrefix)
       .get("email")
       .get(userId)
       .then();
 
-      if (emailEntry === undefined) {
+    if (emailEntry === undefined) {
       return null;
     } else {
       return emailEntry;
@@ -162,15 +163,18 @@ export class P2pDatabaseGunProvider {
   }
 
   public async storePrivateKeyHistory(userId, email, ipfs) {
-    const privateKey = this.gun.get(userId).put({
+    const pvtKey = this.gun.get(userId).put({
       key: ipfs
     });
+    console.log("pvtKey:",pvtKey);
 
     this.gun
       .get(this.osnPrefix)
       .get("privateKey")
-      .set(privateKey);
-
+      .set(pvtKey);
+ 
+   let test = await this.getPvtKeyHistory(userId);
+   console.log("test:",test);
   }
 
   public async getPvtKeyHistory(userId) {
@@ -178,7 +182,7 @@ export class P2pDatabaseGunProvider {
     let entry = await this.gun
       .get(this.osnPrefix)
       .get("privateKey");
-      // console.log("entry:",entry);
+      console.log("entry:",entry);
 
     const pvtKeyEntry = await this.gun
       .get(this.osnPrefix)
@@ -186,7 +190,7 @@ export class P2pDatabaseGunProvider {
       .get(userId)
       .then();
 
-    console.log("private key entry:", pvtKeyEntry);
+    // console.log("private key entry:", pvtKeyEntry);
     if (pvtKeyEntry === undefined) {
       return null;
     } else {
@@ -196,5 +200,5 @@ export class P2pDatabaseGunProvider {
 
 
 
-  
+
 }

+ 8 - 14
app/src/providers/p2p-storage-ipfs/p2p-storage-ipfs.ts

@@ -16,33 +16,27 @@ export class P2pStorageIpfsProvider {
   }
 
   /**
-   * Store public key history on ipfs
-   * @param publicKeyHistory public key history object
+   * Store private key history on ipfs
+   * @param privateKeyHistory private key history object
    */
-  public storePublicKey(publicKeyHistory) {
-    return this.storeOnIPFS(publicKeyHistory);
+  public storePrivateKey(privateKeyHistory) {
+    return this.storeOnIPFS(privateKeyHistory);
   }
+
   private storeOnIPFS(json) {
+    // console.log("json in ipfs.storeOnIPFS is:",json);
     const formData = new FormData();
     formData.append("data", JSON.stringify(json));
 
     return this.http.post(this.infuraUrl + "add", formData).toPromise();
   }
 
-  /**
-   * Store private key history on ipfs
-   * @param privateKeyHistory private key history object
-   */
-  public storePrivateKey(privateKeyHistory) {
-    return this.storeOnIPFS(privateKeyHistory);
-  }
-
-
   /**
    * fetch data from ipfs for hash
    * @param hash address hash
    */
   public async fetchJson(hash: string) {
+    // console.log("hash is:",hash)
     const options = {
       params: { arg: hash }
     };
@@ -63,7 +57,7 @@ export class P2pStorageIpfsProvider {
     try {
       tweet = await this.http.get < string > (this.infuraUrl + "cat", options).toPromise();
     } catch (err) {
-      console.log("failed to resolve get promise",err);
+      console.log("failed to resolve get promise", err);
     }
 
     return tweet;

+ 52 - 29
app/src/providers/pgp-key-server/pgp-key-server.ts

@@ -1,7 +1,6 @@
 import { Injectable } from "@angular/core";
 import { Storage } from "@ionic/storage";
 import * as openpgp from 'openpgp';
-import { P2pDatabaseGunProvider } from "../../providers/p2p-database-gun/p2p-database-gun";
 
 @Injectable()
 export class PgpKeyServerProvider {
@@ -15,9 +14,10 @@ export class PgpKeyServerProvider {
   public async generateKey(passphrase, email) {
     let options = {
       userIds: [{ email: email }], // multiple user IDs
-      curve: "ed25519", // ECC curve name
-      passphrase: this.passphrase // protects the private key
+      curve: "ed25519",// ECC curve name
+      passphrase: this.passphrase
     };
+      // passphrase: this.passphrase // protects the private key
 
     let a = await openpgp.generateKey(options);
     return a;
@@ -25,27 +25,39 @@ export class PgpKeyServerProvider {
 
   public async publishPubKey(pubkey) {
     this.hkp.upload(pubkey).then(function(result) {
-      console.log('public key successfully uploaded',result);
+      // console.log('public key successfully uploaded', result);
     });
   }
 
   public async lookupKeys(email: string) {
     // console.log('looking up keys for',email);
-    var options = {
-      query: email
-    };
-    try{
-      let armoredPubkey = await this.hkp.lookup(options);
-      let pubkey = (await openpgp.key.readArmored(armoredPubkey)).keys[0];
-      this.pk.push(pubkey);
-      return pubkey;
-    }
-    catch(err){
-      console.log("Error: key not found",err);
-      return "Key not found";
-    }
+    let pubkey;
+     let myEmail = await this.storage.get("email");
+     if(email === myEmail){
+        pubkey= await this.storage.get("publicKey");
+        let ampubkey = (await openpgp.key.readArmored(pubkey)).keys[0];
+        this.pk.push(ampubkey);
+     }
+    else{
+        //lookup followers pubkey on server
+            var options = {
+            query: email
+          };
+        try {
+          let armoredPubkey = await this.hkp.lookup(options);
+          pubkey = (await openpgp.key.readArmored(armoredPubkey)).keys[0];
+          // console.log("pubkey from server:",pubkey);
+          this.pk.push(pubkey);  
+          return pubkey;
+        } catch (err) {
+          console.log("Error: key not found");
+
+          }
+      }
+
+    } 
     
-  }
+
 
   /**
    * Encrypt text with RSA
@@ -53,8 +65,8 @@ export class PgpKeyServerProvider {
    * @param privateKey private key
    */
   public async encrypt(plainText) {
-    if(!this.pk){ console.log("this.pk is empty"); return;}
-
+    if (!this.pk) { console.log("this.pk is empty"); return; }
+    console.log("this.pk",this.pk);
     const options = {
       message: openpgp.message.fromText(plainText), // input as Message object
       publicKeys: await Promise.all(this.pk), // for encryption
@@ -64,21 +76,19 @@ export class PgpKeyServerProvider {
     return ciphertext.data;
   }
 
-  public async decrypt(encrypted: string,a) {
-    const privKeyObj = (await openpgp.key.readArmored(a)).keys[0];
-    await privKeyObj.decrypt(this.passphrase);
+  public async decrypt(encrypted: string, privKeyObj) {
+    
     const options2 = {
       message: await openpgp.message.readArmored(encrypted), // parse armored message
       privateKeys: [privKeyObj] // for decryption
     }
-    try{
-       let plaintext = await openpgp.decrypt(options2);
+    try {
+      let plaintext = await openpgp.decrypt(options2);
       return plaintext.data // 'Hello, World!'
+    } catch (err) {
+      console.log('Error thrown:', err);
     }
-     catch(err){
-      console.log('Error thrown:',err);
-    }
-   return null;
+    return null;
   }
 
   public async revokeKey() {
@@ -102,4 +112,17 @@ export class PgpKeyServerProvider {
 
   }
 
+  async getArmoredPrivateKey(key:string){
+    const privKeyObj = (await openpgp.key.readArmored(key)).keys[0];
+    // console.log("key is:",key,'amd',privKeyObj);
+
+    if(privKeyObj){
+      await privKeyObj.decrypt(this.passphrase);
+      // console.log("Key:",key , "Armored key ",privKeyObj);
+      return privKeyObj;
+    }
+    else
+      return key;
+  }
+
 }