crypto.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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. {
  110. name: "RSA-OAEP",
  111. modulusLength: 1024,
  112. publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
  113. hash: { name: "SHA-256" }
  114. },
  115. true,
  116. ["encrypt", "decrypt"]
  117. );
  118. }
  119. public async generatePgpKeys(email){
  120. console.log("this is the mail of the iser ", email);
  121. let options = {
  122. userIds: [{ name: 'Rohithosn', email:email }], // multiple user IDs
  123. curve: "ed25519", // ECC curve name
  124. passphrase: "This is phas" // protects the private key
  125. };
  126. let a = await openpgp.generateKey(options);
  127. console.log('resolved a = ',a);
  128. return a;
  129. // this.privateKey =a.privateKeyArmored;
  130. // this.publicKey = a.publicKeyArmored;
  131. // this.encryptDecryptFunction();
  132. }
  133. /**
  134. * extracts the private key from the key object and transforms it to readable text
  135. * @param keys key object
  136. */
  137. public async extractPrivateKey(keys): Promise<string> {
  138. return btoa(
  139. String.fromCharCode.apply(
  140. null,
  141. new Uint8Array(await crypto.subtle.exportKey("pkcs8", keys.privateKey))
  142. )
  143. );
  144. }
  145. /**
  146. * extracts the public key from the key object and transforms it to readable text
  147. * @param keys key object
  148. */
  149. public async extractPublicKey(keys): Promise<string> {
  150. return btoa(
  151. String.fromCharCode.apply(
  152. null,
  153. new Uint8Array(await crypto.subtle.exportKey("spki", keys.publicKey))
  154. )
  155. );
  156. }
  157. /**
  158. * checks if the latest published key is the same as the one saved in app settings
  159. */
  160. public async isPublicKeyPublished(): Promise<boolean> {
  161. const publicKey = await this.storage.get("publicKey");
  162. return publicKey;
  163. // const keyHistory = await this.getKeyHistory(this.ownUserId);
  164. // if (keyHistory && publicKey.length) {
  165. // const newestPublicKey = keyHistory["keys"].reverse()[0]["key"];
  166. // return newestPublicKey === publicKey;
  167. // } else {
  168. // return false;
  169. // }
  170. }
  171. /**
  172. * checks if a private key is already set
  173. */
  174. public async isPrivateKeySet(): Promise<boolean> {
  175. const privateKey = await this.storage.get("privateKey");
  176. return privateKey;
  177. }
  178. /**
  179. * Encrypt text with RSA
  180. * @param plainText plain text
  181. * @param privateKey private key
  182. */
  183. public encrypt(plainText: string, privateKey: string) {
  184. const key = new NodeRSA(
  185. `-----BEGIN PRIVATE KEY-----${privateKey}-----END PRIVATE KEY-----`
  186. );
  187. return key.encryptPrivate(plainText, "base64");
  188. }
  189. /**
  190. * Decrypt secret with RSA
  191. * @param encryptedMessage encrypted message
  192. * @param publicKey public key
  193. */
  194. public decrypt(encryptedMessage: string, publicKey: string): string {
  195. const key = new NodeRSA(
  196. `-----BEGIN PUBLIC KEY-----${publicKey}-----END PUBLIC KEY-----`
  197. );
  198. return key.decryptPublic(encryptedMessage).toString();
  199. }
  200. /**
  201. * Fetches the public key history for a given user id
  202. * @param userId user id
  203. */
  204. public async fetchPublicKeyHistoryForUser(userId: string): Promise<object[]> {
  205. const keyHistory = await this.getKeyHistory(userId);
  206. return keyHistory["keys"].reverse();
  207. }
  208. private async aesEncrypt(plainText: string) {
  209. const utf8BytesOfPlainText = new TextEncoder().encode(plainText);
  210. const iv = crypto.getRandomValues(new Uint8Array(this.IV_LENGTH));
  211. const keyBytes = this.base64ToBytes(this.HYBRID_OSN_AES_KEY);
  212. const algorithm = { name: "AES-GCM", iv, length: 256 };
  213. return crypto.subtle
  214. .importKey("raw", keyBytes, algorithm, false, ["encrypt"])
  215. .then((cryptoKey: CryptoKey) => {
  216. return crypto.subtle.encrypt(
  217. algorithm,
  218. cryptoKey,
  219. utf8BytesOfPlainText
  220. );
  221. })
  222. .then((encData: ArrayBuffer) =>
  223. this.mergeBytes(iv, this.bufferToBytes(encData))
  224. )
  225. .then(this.bytesToBase64);
  226. }
  227. private aesDecrypt(encryptedMessage: string) {
  228. try {
  229. const ivWithEncryptedBytes = this.base64ToBytes(encryptedMessage);
  230. const { encryptedBytes, ivBytes } = this.splitIvAndEncrypted(
  231. ivWithEncryptedBytes
  232. );
  233. const keyBytes = this.base64ToBytes(this.HYBRID_OSN_AES_KEY);
  234. const algorithm = { name: "AES-GCM", iv: ivBytes, length: 256 };
  235. return crypto.subtle
  236. .importKey("raw", keyBytes, algorithm, false, ["decrypt"])
  237. .then((cryptoKey: CryptoKey) => {
  238. return crypto.subtle.decrypt(algorithm, cryptoKey, encryptedBytes);
  239. })
  240. .then((decryptedData: ArrayBuffer) => {
  241. return new TextDecoder().decode(decryptedData);
  242. });
  243. } catch (e) {
  244. return Promise.reject(e);
  245. }
  246. }
  247. private bufferToBytes(arrayBuffer: ArrayBuffer) {
  248. return new Uint8Array(arrayBuffer);
  249. }
  250. private bytesToBase64(bytes: Uint8Array): string {
  251. let binary = "";
  252. const len = bytes.length;
  253. for (let i = 0; i < len; i++) {
  254. binary += String.fromCharCode(bytes[i]);
  255. }
  256. return btoa(binary);
  257. }
  258. private base64ToBytes(base64: string): Uint8Array {
  259. const binaryString = atob(base64);
  260. const len = binaryString.length;
  261. const bytes = new Uint8Array(len);
  262. for (let i = 0; i < len; i++) {
  263. bytes[i] = binaryString.charCodeAt(i);
  264. }
  265. return bytes;
  266. }
  267. private mergeBytes(a: Uint8Array, b: Uint8Array) {
  268. const aLen = a.length;
  269. const bLen = b.length;
  270. const res = new Uint8Array(aLen + bLen);
  271. for (let i = 0; i < aLen; i++) {
  272. res[i] = a[i];
  273. }
  274. for (let i = 0; i < bLen; i++) {
  275. res[i + aLen] = b[i];
  276. }
  277. return res;
  278. }
  279. private splitIvAndEncrypted(ivWithEncryptedBytes: Uint8Array) {
  280. const dataLen = ivWithEncryptedBytes.length;
  281. const ivBytes = new Uint8Array(this.IV_LENGTH);
  282. const encryptedBytes = new Uint8Array(dataLen - this.IV_LENGTH);
  283. for (let i = 0; i < this.IV_LENGTH; i++) {
  284. ivBytes[i] = ivWithEncryptedBytes[i];
  285. }
  286. for (let i = this.IV_LENGTH; i < dataLen; i++) {
  287. encryptedBytes[i - this.IV_LENGTH] = ivWithEncryptedBytes[i];
  288. }
  289. return { ivBytes, encryptedBytes };
  290. }
  291. }