crypto.ts 8.0 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. const tweetWithKeyHistoryLink = await this.twitter.fetchTweet(tweetId);
  60. // Extract link to public key
  61. const link = this.extractLinkFromDescription(
  62. tweetWithKeyHistoryLink["data"]["full_text"]
  63. );
  64. // Fetch public key history
  65. if (link.length) {
  66. const encryptedKeyHistory = await this.ipfs.fetchJson(link);
  67. // Decrypt key history
  68. const keyHistory = await this.aesDecrypt(encryptedKeyHistory.toString());
  69. return JSON.parse(keyHistory);
  70. } else {
  71. return null;
  72. }
  73. }
  74. private extractTweetId(text: string) {
  75. for (let word of text.split(" ")) {
  76. if (this.isTweetId(word)) {
  77. return word.substr(8);
  78. }
  79. }
  80. return "";
  81. }
  82. private extractLinkFromDescription(text: string): string {
  83. for (let word of text.split(" ")) {
  84. if (this.isIpfsLink(word)) {
  85. return word.substr(7);
  86. }
  87. }
  88. return "";
  89. }
  90. private isIpfsLink(word: string): boolean {
  91. const hits = word.match(/ipfs:\/\/Qm[a-zA-Z0-9]+/);
  92. return hits != null;
  93. }
  94. private isTweetId(word: string): boolean {
  95. const hits = word.match(/tweet:\/\/[0-9]+/);
  96. return hits != null;
  97. }
  98. public async generateRsaKeys() {
  99. return await crypto.subtle.generateKey(
  100. {
  101. name: "RSA-OAEP",
  102. modulusLength: 1024,
  103. publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
  104. hash: { name: "SHA-256" }
  105. },
  106. true,
  107. ["encrypt", "decrypt"]
  108. );
  109. }
  110. public async extractPrivateKey(keys): Promise<string> {
  111. return btoa(
  112. String.fromCharCode.apply(
  113. null,
  114. new Uint8Array(await crypto.subtle.exportKey("pkcs8", keys.privateKey))
  115. )
  116. );
  117. }
  118. public async extractPublicKey(keys): Promise<string> {
  119. return btoa(
  120. String.fromCharCode.apply(
  121. null,
  122. new Uint8Array(await crypto.subtle.exportKey("spki", keys.publicKey))
  123. )
  124. );
  125. }
  126. public async isPublicKeyPublished(): Promise<boolean> {
  127. const publicKey = await this.storage.get("publicKey");
  128. const keyHistory = await this.getKeyHistory(this.ownUserId);
  129. if (keyHistory && publicKey.length) {
  130. const newestPublicKey = keyHistory["keys"].reverse()[0]["key"];
  131. return newestPublicKey === publicKey;
  132. } else {
  133. return false;
  134. }
  135. }
  136. public async isPrivateKeySet(): Promise<boolean> {
  137. const privateKey = await this.storage.get("privateKey");
  138. return privateKey;
  139. }
  140. public encrypt(plainText: string, privateKey: string) {
  141. const key = new NodeRSA(
  142. `-----BEGIN PRIVATE KEY-----${privateKey}-----END PRIVATE KEY-----`
  143. );
  144. return key.encryptPrivate(plainText, "base64");
  145. }
  146. public decrypt(encryptedMessage: string, publicKey: string): string {
  147. const key = new NodeRSA(
  148. `-----BEGIN PUBLIC KEY-----${publicKey}-----END PUBLIC KEY-----`
  149. );
  150. return key.decryptPublic(encryptedMessage).toString();
  151. }
  152. public async fetchPublicKeyHistoryForUser(userId: string): Promise<object[]> {
  153. const keyHistory = await this.getKeyHistory(userId);
  154. return keyHistory["keys"].reverse();
  155. }
  156. private async aesEncrypt(plainText: string) {
  157. const utf8BytesOfPlainText = new TextEncoder().encode(plainText);
  158. const iv = crypto.getRandomValues(new Uint8Array(this.IV_LENGTH));
  159. const keyBytes = this.base64ToBytes(this.HYBRID_OSN_AES_KEY);
  160. const algorithm = { name: "AES-GCM", iv, length: 256 };
  161. return crypto.subtle
  162. .importKey("raw", keyBytes, algorithm, false, ["encrypt"])
  163. .then((cryptoKey: CryptoKey) => {
  164. return crypto.subtle.encrypt(
  165. algorithm,
  166. cryptoKey,
  167. utf8BytesOfPlainText
  168. );
  169. })
  170. .then((encData: ArrayBuffer) => {
  171. // prepend the iv to the bytes, so that decryption-process can use it, see markdown file for "AES (symm.) encryption" and "AES Initialization vector (iv)"
  172. return 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. }