settings.ts 1.9 KB

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