PGP.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. import * as kbpgp from "kbpgp";
  2. import {promisify} from "es6-promisify";
  3. /**
  4. * PGP operations.
  5. *
  6. * @author tlwr [toby@toby.codes]
  7. * @author Matt C [matt@artemisbot.uk]
  8. * @author n1474335 [n1474335@gmail.com]
  9. * @copyright Crown Copyright 2017
  10. * @license Apache-2.0
  11. *
  12. * @namespace
  13. */
  14. const PGP = {
  15. /**
  16. * @constant
  17. * @default
  18. */
  19. KEY_TYPES: ["RSA-1024", "RSA-2048", "RSA-4096", "ECC-256", "ECC-384"],
  20. /**
  21. * Get size of subkey
  22. *
  23. * @private
  24. * @param {number} keySize
  25. * @returns {number}
  26. */
  27. _getSubkeySize(keySize) {
  28. return {
  29. 1024: 1024,
  30. 2048: 1024,
  31. 4096: 2048,
  32. 256: 256,
  33. 384: 256,
  34. }[keySize];
  35. },
  36. /**
  37. * Progress callback
  38. *
  39. * @private
  40. */
  41. _ASP: new kbpgp.ASP({
  42. "progress_hook": info => {
  43. let msg = "";
  44. switch (info.what) {
  45. case "guess":
  46. msg = "Guessing a prime";
  47. break;
  48. case "fermat":
  49. msg = "Factoring prime using Fermat's factorization method";
  50. break;
  51. case "mr":
  52. msg = "Performing Miller-Rabin primality test";
  53. break;
  54. case "passed_mr":
  55. msg = "Passed Miller-Rabin primality test";
  56. break;
  57. case "failed_mr":
  58. msg = "Failed Miller-Rabin primality test";
  59. break;
  60. case "found":
  61. msg = "Prime found";
  62. break;
  63. default:
  64. msg = `Stage: ${info.what}`;
  65. }
  66. if (ENVIRONMENT_IS_WORKER())
  67. self.sendStatusMessage(msg);
  68. }
  69. }),
  70. /**
  71. * Import private key and unlock if necessary
  72. *
  73. * @private
  74. * @param {string} privateKey
  75. * @param {string} [passphrase]
  76. * @returns {Object}
  77. */
  78. async _importPrivateKey(privateKey, passphrase) {
  79. try {
  80. const key = await promisify(kbpgp.KeyManager.import_from_armored_pgp)({
  81. armored: privateKey,
  82. opts: {
  83. "no_check_keys": true
  84. }
  85. });
  86. if (key.is_pgp_locked()) {
  87. if (passphrase) {
  88. await promisify(key.unlock_pgp.bind(key))({
  89. passphrase
  90. });
  91. } else {
  92. throw "Did not provide passphrase with locked private key.";
  93. }
  94. }
  95. return key;
  96. } catch (err) {
  97. throw `Could not import private key: ${err}`;
  98. }
  99. },
  100. /**
  101. * Import public key
  102. *
  103. * @private
  104. * @param {string} publicKey
  105. * @returns {Object}
  106. */
  107. async _importPublicKey (publicKey) {
  108. try {
  109. const key = await promisify(kbpgp.KeyManager.import_from_armored_pgp)({
  110. armored: publicKey,
  111. opts: {
  112. "no_check_keys": true
  113. }
  114. });
  115. return key;
  116. } catch (err) {
  117. throw `Could not import public key: ${err}`;
  118. }
  119. },
  120. /**
  121. * Generate PGP Key Pair operation.
  122. *
  123. * @param {string} input
  124. * @param {Object[]} args
  125. * @returns {string}
  126. */
  127. runGenerateKeyPair(input, args) {
  128. let [keyType, keySize] = args[0].split("-"),
  129. password = args[1],
  130. name = args[2],
  131. email = args[3],
  132. userIdentifier = "";
  133. if (name) userIdentifier += name;
  134. if (email) userIdentifier += ` <${email}>`;
  135. let flags = kbpgp.const.openpgp.certify_keys;
  136. flags |= kbpgp.const.openpgp.sign_data;
  137. flags |= kbpgp.const.openpgp.auth;
  138. flags |= kbpgp.const.openpgp.encrypt_comm;
  139. flags |= kbpgp.const.openpgp.encrypt_storage;
  140. let keyGenerationOptions = {
  141. userid: userIdentifier,
  142. ecc: keyType === "ecc",
  143. primary: {
  144. "nbits": keySize,
  145. "flags": flags,
  146. "expire_in": 0
  147. },
  148. subkeys: [{
  149. "nbits": PGP._getSubkeySize(keySize),
  150. "flags": kbpgp.const.openpgp.sign_data,
  151. "expire_in": 86400 * 365 * 8
  152. }, {
  153. "nbits": PGP._getSubkeySize(keySize),
  154. "flags": kbpgp.const.openpgp.encrypt_comm | kbpgp.const.openpgp.encrypt_storage,
  155. "expire_in": 86400 * 365 * 2
  156. }],
  157. asp: PGP._ASP
  158. };
  159. return new Promise(async (resolve, reject) => {
  160. try {
  161. const unsignedKey = await promisify(kbpgp.KeyManager.generate)(keyGenerationOptions);
  162. await promisify(unsignedKey.sign.bind(unsignedKey))({});
  163. let signedKey = unsignedKey;
  164. let privateKeyExportOptions = {};
  165. if (password) privateKeyExportOptions.passphrase = password;
  166. const privateKey = await promisify(signedKey.export_pgp_private.bind(signedKey))(privateKeyExportOptions);
  167. const publicKey = await promisify(signedKey.export_pgp_public.bind(signedKey))({});
  168. resolve(privateKey + "\n" + publicKey.trim());
  169. } catch (err) {
  170. reject(`Error whilst generating key pair: ${err}`);
  171. }
  172. });
  173. },
  174. /**
  175. * PGP Encrypt operation.
  176. *
  177. * @param {string} input
  178. * @param {Object[]} args
  179. * @returns {string}
  180. */
  181. async runEncrypt(input, args) {
  182. let plaintextMessage = input,
  183. plainPubKey = args[0],
  184. key,
  185. encryptedMessage;
  186. if (!plainPubKey) return "Enter the public key of the recipient.";
  187. try {
  188. key = await promisify(kbpgp.KeyManager.import_from_armored_pgp)({
  189. armored: plainPubKey,
  190. });
  191. } catch (err) {
  192. throw `Could not import public key: ${err}`;
  193. }
  194. try {
  195. encryptedMessage = await promisify(kbpgp.box)({
  196. "msg": plaintextMessage,
  197. "encrypt_for": key,
  198. "asp": PGP._ASP
  199. });
  200. } catch (err) {
  201. throw `Couldn't encrypt message with provided public key: ${err}`;
  202. }
  203. return encryptedMessage.toString();
  204. },
  205. /**
  206. * PGP Decrypt operation.
  207. *
  208. * @param {string} input
  209. * @param {Object[]} args
  210. * @returns {string}
  211. */
  212. async runDecrypt(input, args) {
  213. let encryptedMessage = input,
  214. privateKey = args[0],
  215. passphrase = args[1],
  216. keyring = new kbpgp.keyring.KeyRing(),
  217. plaintextMessage;
  218. if (!privateKey) return "Enter the private key of the recipient.";
  219. const key = await PGP._importPrivateKey(privateKey, passphrase);
  220. keyring.add_key_manager(key);
  221. try {
  222. plaintextMessage = await promisify(kbpgp.unbox)({
  223. armored: encryptedMessage,
  224. keyfetch: keyring,
  225. asp: PGP._ASP
  226. });
  227. } catch (err) {
  228. throw `Couldn't decrypt message with provided private key: ${err}`;
  229. }
  230. return plaintextMessage.toString();
  231. },
  232. /**
  233. * PGP Sign Message operation.
  234. *
  235. * @param {string} input
  236. * @param {Object[]} args
  237. * @returns {string}
  238. */
  239. async runSign(input, args) {
  240. let message = input,
  241. privateKey = args[0],
  242. passphrase = args[1],
  243. publicKey = args[2],
  244. signedMessage;
  245. if (!privateKey) return "Enter the private key of the signer.";
  246. if (!publicKey) return "Enter the public key of the recipient.";
  247. const privKey = await PGP._importPrivateKey(privateKey, passphrase);
  248. const pubKey = await PGP._importPublicKey(publicKey);
  249. try {
  250. signedMessage = await promisify(kbpgp.box)({
  251. "msg": message,
  252. "encrypt_for": pubKey,
  253. "sign_with": privKey,
  254. "asp": PGP._ASP
  255. });
  256. } catch (err) {
  257. throw `Couldn't sign message: ${err}`;
  258. }
  259. return signedMessage;
  260. },
  261. /**
  262. * PGP Verify Message operation.
  263. *
  264. * @param {string} input
  265. * @param {Object[]} args
  266. * @returns {string}
  267. */
  268. async runVerify(input, args) {
  269. let signedMessage = input,
  270. publicKey = args[0],
  271. privateKey = args[1],
  272. passphrase = args[2],
  273. keyring = new kbpgp.keyring.KeyRing(),
  274. unboxedLiterals;
  275. if (!publicKey) return "Enter the public key of the signer.";
  276. if (!privateKey) return "Enter the private key of the recipient.";
  277. const privKey = await PGP._importPrivateKey(privateKey, passphrase);
  278. const pubKey = await PGP._importPublicKey(publicKey);
  279. keyring.add_key_manager(privKey);
  280. keyring.add_key_manager(pubKey);
  281. try {
  282. unboxedLiterals = await promisify(kbpgp.unbox)({
  283. armored: signedMessage,
  284. keyfetch: keyring,
  285. asp: PGP._ASP
  286. });
  287. const ds = unboxedLiterals[0].get_data_signer();
  288. if (ds) {
  289. const km = ds.get_key_manager();
  290. if (km) {
  291. const signer = km.get_userids_mark_primary()[0].components;
  292. let text = "Signed by ";
  293. if (signer.email || signer.username || signer.comment) {
  294. if (signer.username) {
  295. text += `${signer.username} `;
  296. }
  297. if (signer.comment) {
  298. text += `${signer.comment} `;
  299. }
  300. if (signer.email) {
  301. text += `<${signer.email}>`;
  302. }
  303. text += "\n";
  304. }
  305. text += [
  306. `PGP fingerprint: ${km.get_pgp_fingerprint().toString("hex")}`,
  307. `Signed on ${new Date(ds.sig.hashed_subpackets[0].time * 1000).toUTCString()}`,
  308. "----------------------------------\n"
  309. ].join("\n");
  310. text += unboxedLiterals.toString();
  311. return text.trim();
  312. } else {
  313. return "Could not identify a key manager.";
  314. }
  315. } else {
  316. return "The data does not appear to be signed.";
  317. }
  318. } catch (err) {
  319. return `Couldn't verify message: ${err}`;
  320. }
  321. },
  322. };
  323. export default PGP;