import { Injectable } from "@angular/core"; import { Storage } from "@ionic/storage"; import * as openpgp from 'openpgp'; @Injectable() export class PgpKeyServerProvider { hkp = new openpgp.HKP('https://sks-keyservers.net/'); pk: any[] = []; passphrase = "passphrase"; constructor(private storage: Storage) {} 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 }; let a = await openpgp.generateKey(options); console.log('the key generated is:', a); return a; } public async publishPubKey(pubkey) { console.log('passing pubkey to uplaoded : ', pubkey); this.hkp.upload(pubkey).then(function() { console.log('public key successfully uploaded'); }); } public async lookupKeys(email: string) { console.log('looking up keys for',email); var options = { query: email }; let armoredPubkey = await this.hkp.lookup(options); let pubkey = (await openpgp.key.readArmored(armoredPubkey)).keys[0]; console.log('Found latest public key:', pubkey); this.pk.push(pubkey); console.log('pk is:', this.pk); } /** * Encrypt text with RSA * @param plainText plain text * @param privateKey private key */ public async encrypt(plainText: string) { // this.lookupKeys('rohit.shiva.gowda@gmail.com'); const options = { message: openpgp.message.fromText(plainText), // input as Message object publicKeys: await Promise.all(this.pk), // for encryption // privateKey s: [privKeyObj] // for signing (optional) } console.log('options are:', options); const ciphertext = await openpgp.encrypt(options); console.log('encrypted text is:', ciphertext); return ciphertext.data; } public async decrypt(encrypted: string,a) { const privKeyObj = (await openpgp.key.readArmored(a)).keys[0]; console.log('privKeyObj', privKeyObj); await privKeyObj.decrypt(this.passphrase); console.log('a is:',a); const options2 = { message: await openpgp.message.readArmored(encrypted), // parse armored message privateKeys: [privKeyObj] // 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 revokeKey() { //using revocation certificate let pubkey = await this.storage.get("publicKey"); let atest = (await openpgp.key.readArmored(pubkey)).keys[0]; console.log('inside revoke key pubkey is:', atest); let revocatnCert = this.storage.get("revocationCert"); try { var options = { key: atest, revocationCertificate: revocatnCert }; openpgp.revokeKey(options).then(function(key) { console.log("public key revoked", key); }); } catch (e) { console.log('revoke failed1', e); } } }