crypto.ts 9.0 KB

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