crypto.ts 8.7 KB

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