settings.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import { Component } from "@angular/core";
  2. import { NavController, ToastController } from "ionic-angular";
  3. import { Storage } from "@ionic/storage";
  4. import { CryptoProvider } from "../../providers/crypto/crypto";
  5. @Component({
  6. selector: "page-settings",
  7. templateUrl: "settings.html"
  8. })
  9. export class SettingsPage {
  10. keywords: string;
  11. privateKey: string;
  12. publicKey: string;
  13. constructor(
  14. public navCtrl: NavController,
  15. public toastCtrl: ToastController,
  16. private cryptoUtils: CryptoProvider,
  17. private storage: Storage
  18. ) {
  19. this.loadValuesFromStorage();
  20. }
  21. async loadValuesFromStorage() {
  22. this.privateKey = await this.storage.get("privateKey");
  23. this.publicKey = await this.storage.get("publicKey");
  24. this.keywords = await this.storage.get("keywords");
  25. }
  26. async generateKeys() {
  27. const keys = await this.generateRsaKeys();
  28. this.publicKey = await this.extractPublicKey(keys);
  29. this.privateKey = await this.extractPrivateKey(keys);
  30. }
  31. save() {
  32. this.storage.set("publicKey", this.publicKey);
  33. this.storage.set("privateKey", this.privateKey);
  34. this.storage.set("keywords", this.keywords);
  35. const toast = this.toastCtrl.create({
  36. message: "Successfully saved!",
  37. position: "bottom",
  38. duration: 3000
  39. });
  40. toast.present();
  41. }
  42. publishPublicKey() {
  43. this.cryptoUtils.publishPublicKey(this.publicKey);
  44. }
  45. private async generateRsaKeys() {
  46. return await crypto.subtle.generateKey(
  47. {
  48. name: "RSA-OAEP",
  49. modulusLength: 1024,
  50. publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
  51. hash: { name: "SHA-256" }
  52. },
  53. true,
  54. ["encrypt", "decrypt"]
  55. );
  56. }
  57. private async extractPrivateKey(keys): Promise<string> {
  58. return btoa(
  59. String.fromCharCode.apply(
  60. null,
  61. new Uint8Array(await crypto.subtle.exportKey("pkcs8", keys.privateKey))
  62. )
  63. );
  64. }
  65. private async extractPublicKey(keys): Promise<string> {
  66. return btoa(
  67. String.fromCharCode.apply(
  68. null,
  69. new Uint8Array(await crypto.subtle.exportKey("spki", keys.publicKey))
  70. )
  71. );
  72. }
  73. }