crypto.ts 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. import { Injectable } from "@angular/core";
  2. import { TwitterApiProvider } from "../twitter-api/twitter-api";
  3. import { P2pStorageIpfsProvider } from "../p2p-storage-ipfs/p2p-storage-ipfs";
  4. import { Storage } from "@ionic/storage";
  5. import NodeRSA from "node-rsa";
  6. @Injectable()
  7. export class CryptoProvider {
  8. ownUserId: string;
  9. constructor(
  10. private twitter: TwitterApiProvider,
  11. private ipfs: P2pStorageIpfsProvider,
  12. private storage: Storage
  13. ) {
  14. this.init();
  15. }
  16. private async init() {
  17. this.ownUserId = await this.storage.get("userId");
  18. }
  19. public async publishPublicKey(key: string) {
  20. let publicKeyHistory = await this.getKeyHistory(this.ownUserId);
  21. // Todo: avoid publishing the same public key twice - check if new key equals newest key in history
  22. // Add new key to history
  23. const newKey = {
  24. key: key,
  25. validFrom: Date.now()
  26. };
  27. if (publicKeyHistory) {
  28. publicKeyHistory["keys"].push(newKey);
  29. } else {
  30. publicKeyHistory = {
  31. keys: [newKey]
  32. };
  33. }
  34. // TODO: encrypt key history with AES
  35. // Publish updated key history...
  36. const res = await this.ipfs.storePublicKey(publicKeyHistory);
  37. // tweet ipfs link
  38. const tweetResponse = await this.twitter.tweet(
  39. "ipfs://" + res["Hash"] + " #hybridOSN"
  40. );
  41. // ... and update description in user profile with tweet id
  42. this.twitter.updateProfileDescription(
  43. "tweet://" + tweetResponse["data"]["id_str"] + " #hybridOSN"
  44. );
  45. }
  46. private async getKeyHistory(userId: string) {
  47. // Get user description
  48. const userData = await this.twitter.fetchUser(userId);
  49. const profileDescription = userData["description"];
  50. // Get tweet with link to key history
  51. const tweetId = this.extractTweetId(profileDescription);
  52. const tweetWithKeyHistoryLink = await this.twitter.fetchTweet(tweetId);
  53. // Extract link to public key
  54. const link = this.extractLinkFromDescription(
  55. tweetWithKeyHistoryLink["data"]["full_text"]
  56. );
  57. // Fetch public key history
  58. if (link.length) {
  59. const keyHistory = await this.ipfs.fetchJson(link);
  60. // TODO: dedcrypt key history with AES
  61. return keyHistory;
  62. } else {
  63. return null;
  64. }
  65. }
  66. private extractTweetId(text: string) {
  67. for (let word of text.split(" ")) {
  68. if (this.isTweetId(word)) {
  69. return word.substr(8);
  70. }
  71. }
  72. return "";
  73. }
  74. private extractLinkFromDescription(text: string): string {
  75. for (let word of text.split(" ")) {
  76. if (this.isIpfsLink(word)) {
  77. return word.substr(7);
  78. }
  79. }
  80. return "";
  81. }
  82. private isIpfsLink(word: string): boolean {
  83. const hits = word.match(/ipfs:\/\/Qm[a-zA-Z0-9]+/);
  84. return hits != null;
  85. }
  86. private isTweetId(word: string): boolean {
  87. const hits = word.match(/tweet:\/\/[0-9]+/);
  88. return hits != null;
  89. }
  90. public async generateRsaKeys() {
  91. return await crypto.subtle.generateKey(
  92. {
  93. name: "RSA-OAEP",
  94. modulusLength: 1024,
  95. publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
  96. hash: { name: "SHA-256" }
  97. },
  98. true,
  99. ["encrypt", "decrypt"]
  100. );
  101. }
  102. public async extractPrivateKey(keys): Promise<string> {
  103. return btoa(
  104. String.fromCharCode.apply(
  105. null,
  106. new Uint8Array(await crypto.subtle.exportKey("pkcs8", keys.privateKey))
  107. )
  108. );
  109. }
  110. public async extractPublicKey(keys): Promise<string> {
  111. return btoa(
  112. String.fromCharCode.apply(
  113. null,
  114. new Uint8Array(await crypto.subtle.exportKey("spki", keys.publicKey))
  115. )
  116. );
  117. }
  118. public async isPublicKeyPublished(): Promise<boolean> {
  119. const publicKey = await this.storage.get("publicKey");
  120. const keyHistory = await this.getKeyHistory(this.ownUserId);
  121. if (keyHistory && publicKey.length) {
  122. const newestPublicKey = keyHistory["keys"].reverse()[0]["key"];
  123. return newestPublicKey === publicKey;
  124. } else {
  125. return false;
  126. }
  127. }
  128. public async isPrivateKeySet(): Promise<boolean> {
  129. const privateKey = await this.storage.get("privateKey");
  130. return privateKey.length > 0;
  131. }
  132. public encrypt(plainText: string, privateKey: string) {
  133. const key = new NodeRSA(
  134. `-----BEGIN PRIVATE KEY-----${privateKey}-----END PRIVATE KEY-----`
  135. );
  136. return key.encryptPrivate(plainText, "base64");
  137. }
  138. public decrypt(encryptedMessage: string, publicKey: string): string {
  139. const key = new NodeRSA(
  140. `-----BEGIN PUBLIC KEY-----${publicKey}-----END PUBLIC KEY-----`
  141. );
  142. return key.decryptPublic(encryptedMessage).toString();
  143. }
  144. public async fetchPublicKeyHistoryForUser(userId: string): Promise<object[]> {
  145. const keyHistory = await this.getKeyHistory(userId);
  146. return keyHistory["keys"].reverse();
  147. }
  148. }