crypto.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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. declare var TextDecoder: any;
  7. declare var TextEncoder: any;
  8. @Injectable()
  9. export class CryptoProvider {
  10. ownUserId: string;
  11. IV_LENGTH = 12;
  12. HYBRID_OSN_AES_KEY = "Z1vxAULQnZdoWhJOvv+hWEvVpyUHzNjD/ichEE2c8i4=";
  13. constructor(
  14. private twitter: TwitterApiProvider,
  15. private ipfs: P2pStorageIpfsProvider,
  16. private storage: Storage
  17. ) {
  18. this.init();
  19. }
  20. private async init() {
  21. this.ownUserId = await this.storage.get("userId");
  22. }
  23. public async publishPublicKey(key: string) {
  24. let publicKeyHistory = await this.getKeyHistory(this.ownUserId);
  25. // Todo: avoid publishing the same public key twice - check if new key equals newest key in history
  26. // Add new key to history
  27. const newKey = {
  28. key: key,
  29. validFrom: Date.now()
  30. };
  31. if (publicKeyHistory) {
  32. publicKeyHistory["keys"].push(newKey);
  33. } else {
  34. publicKeyHistory = {
  35. keys: [newKey]
  36. };
  37. }
  38. // Ecnrypt key history
  39. const encryptedPublicKeyHistory = await this.aesEncrypt(
  40. JSON.stringify(publicKeyHistory)
  41. );
  42. // Publish updated key history...
  43. const res = await this.ipfs.storePublicKey(encryptedPublicKeyHistory);
  44. // tweet ipfs link
  45. const tweetResponse = await this.twitter.tweet(
  46. "ipfs://" + res["Hash"] + " #hybridOSN"
  47. );
  48. // ... and update description in user profile with tweet id
  49. this.twitter.updateProfileDescription(
  50. "tweet://" + tweetResponse["data"]["id_str"] + " #hybridOSN"
  51. );
  52. }
  53. private async getKeyHistory(userId: string) {
  54. // Get user description
  55. const userData = await this.twitter.fetchUser(userId);
  56. const profileDescription = userData["description"];
  57. // Get tweet with link to key history
  58. const tweetId = this.extractTweetId(profileDescription);
  59. if (tweetId.length === 0) {
  60. return null;
  61. }
  62. const tweetWithKeyHistoryLink = await this.twitter.fetchTweet(tweetId);
  63. // Extract link to public key
  64. const link = this.extractLinkFromDescription(
  65. tweetWithKeyHistoryLink["data"]["full_text"]
  66. );
  67. // Fetch public key history
  68. if (link.length) {
  69. const encryptedKeyHistory = await this.ipfs.fetchJson(link);
  70. // Decrypt key history
  71. const keyHistory = await this.aesDecrypt(encryptedKeyHistory.toString());
  72. return JSON.parse(keyHistory);
  73. } else {
  74. return null;
  75. }
  76. }
  77. private extractTweetId(text: string): string {
  78. for (let word of text.split(" ")) {
  79. if (this.isTweetId(word)) {
  80. return word.substr(8);
  81. }
  82. }
  83. return "";
  84. }
  85. private extractLinkFromDescription(text: string): string {
  86. for (let word of text.split(" ")) {
  87. if (this.isIpfsLink(word)) {
  88. return word.substr(7);
  89. }
  90. }
  91. return "";
  92. }
  93. private isIpfsLink(word: string): boolean {
  94. return /ipfs:\/\/Qm[a-zA-Z0-9]+/.test(word);
  95. }
  96. private isTweetId(word: string): boolean {
  97. return /tweet:\/\/[0-9]+/.test(word);
  98. }
  99. public async generateRsaKeys() {
  100. return await crypto.subtle.generateKey(
  101. {
  102. name: "RSA-OAEP",
  103. modulusLength: 1024,
  104. publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
  105. hash: { name: "SHA-256" }
  106. },
  107. true,
  108. ["encrypt", "decrypt"]
  109. );
  110. }
  111. public async extractPrivateKey(keys): Promise<string> {
  112. return btoa(
  113. String.fromCharCode.apply(
  114. null,
  115. new Uint8Array(await crypto.subtle.exportKey("pkcs8", keys.privateKey))
  116. )
  117. );
  118. }
  119. public async extractPublicKey(keys): Promise<string> {
  120. return btoa(
  121. String.fromCharCode.apply(
  122. null,
  123. new Uint8Array(await crypto.subtle.exportKey("spki", keys.publicKey))
  124. )
  125. );
  126. }
  127. public async isPublicKeyPublished(): Promise<boolean> {
  128. const publicKey = await this.storage.get("publicKey");
  129. const keyHistory = await this.getKeyHistory(this.ownUserId);
  130. if (keyHistory && publicKey.length) {
  131. const newestPublicKey = keyHistory["keys"].reverse()[0]["key"];
  132. return newestPublicKey === publicKey;
  133. } else {
  134. return false;
  135. }
  136. }
  137. public async isPrivateKeySet(): Promise<boolean> {
  138. const privateKey = await this.storage.get("privateKey");
  139. return privateKey;
  140. }
  141. public encrypt(plainText: string, privateKey: string) {
  142. const key = new NodeRSA(
  143. `-----BEGIN PRIVATE KEY-----${privateKey}-----END PRIVATE KEY-----`
  144. );
  145. return key.encryptPrivate(plainText, "base64");
  146. }
  147. public decrypt(encryptedMessage: string, publicKey: string): string {
  148. const key = new NodeRSA(
  149. `-----BEGIN PUBLIC KEY-----${publicKey}-----END PUBLIC KEY-----`
  150. );
  151. return key.decryptPublic(encryptedMessage).toString();
  152. }
  153. public async fetchPublicKeyHistoryForUser(userId: string): Promise<object[]> {
  154. const keyHistory = await this.getKeyHistory(userId);
  155. return keyHistory["keys"].reverse();
  156. }
  157. private async aesEncrypt(plainText: string) {
  158. const utf8BytesOfPlainText = new TextEncoder().encode(plainText);
  159. const iv = crypto.getRandomValues(new Uint8Array(this.IV_LENGTH));
  160. const keyBytes = this.base64ToBytes(this.HYBRID_OSN_AES_KEY);
  161. const algorithm = { name: "AES-GCM", iv, length: 256 };
  162. return crypto.subtle
  163. .importKey("raw", keyBytes, algorithm, false, ["encrypt"])
  164. .then((cryptoKey: CryptoKey) => {
  165. return crypto.subtle.encrypt(
  166. algorithm,
  167. cryptoKey,
  168. utf8BytesOfPlainText
  169. );
  170. })
  171. .then((encData: ArrayBuffer) =>
  172. this.mergeBytes(iv, this.bufferToBytes(encData))
  173. )
  174. .then(this.bytesToBase64);
  175. }
  176. private aesDecrypt(encryptedMessage: string) {
  177. try {
  178. const ivWithEncryptedBytes = this.base64ToBytes(encryptedMessage);
  179. const { encryptedBytes, ivBytes } = this.splitIvAndEncrypted(
  180. ivWithEncryptedBytes
  181. );
  182. const keyBytes = this.base64ToBytes(this.HYBRID_OSN_AES_KEY);
  183. const algorithm = { name: "AES-GCM", iv: ivBytes, length: 256 };
  184. return crypto.subtle
  185. .importKey("raw", keyBytes, algorithm, false, ["decrypt"])
  186. .then((cryptoKey: CryptoKey) => {
  187. return crypto.subtle.decrypt(algorithm, cryptoKey, encryptedBytes);
  188. })
  189. .then((decryptedData: ArrayBuffer) => {
  190. return new TextDecoder().decode(decryptedData);
  191. });
  192. } catch (e) {
  193. return Promise.reject(e);
  194. }
  195. }
  196. private bufferToBytes(arrayBuffer: ArrayBuffer) {
  197. return new Uint8Array(arrayBuffer);
  198. }
  199. private bytesToBase64(bytes: Uint8Array): string {
  200. let binary = "";
  201. const len = bytes.length;
  202. for (let i = 0; i < len; i++) {
  203. binary += String.fromCharCode(bytes[i]);
  204. }
  205. return btoa(binary);
  206. }
  207. private base64ToBytes(base64: string): Uint8Array {
  208. const binaryString = atob(base64);
  209. const len = binaryString.length;
  210. const bytes = new Uint8Array(len);
  211. for (let i = 0; i < len; i++) {
  212. bytes[i] = binaryString.charCodeAt(i);
  213. }
  214. return bytes;
  215. }
  216. private mergeBytes(a: Uint8Array, b: Uint8Array) {
  217. const aLen = a.length;
  218. const bLen = b.length;
  219. const res = new Uint8Array(aLen + bLen);
  220. for (let i = 0; i < aLen; i++) {
  221. res[i] = a[i];
  222. }
  223. for (let i = 0; i < bLen; i++) {
  224. res[i + aLen] = b[i];
  225. }
  226. return res;
  227. }
  228. private splitIvAndEncrypted(ivWithEncryptedBytes: Uint8Array) {
  229. const dataLen = ivWithEncryptedBytes.length;
  230. const ivBytes = new Uint8Array(this.IV_LENGTH);
  231. const encryptedBytes = new Uint8Array(dataLen - this.IV_LENGTH);
  232. for (let i = 0; i < this.IV_LENGTH; i++) {
  233. ivBytes[i] = ivWithEncryptedBytes[i];
  234. }
  235. for (let i = this.IV_LENGTH; i < dataLen; i++) {
  236. encryptedBytes[i - this.IV_LENGTH] = ivWithEncryptedBytes[i];
  237. }
  238. return { ivBytes, encryptedBytes };
  239. }
  240. }