pkcs7.js 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243
  1. /**
  2. * Javascript implementation of PKCS#7 v1.5.
  3. *
  4. * @author Stefan Siegl
  5. * @author Dave Longley
  6. *
  7. * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>
  8. * Copyright (c) 2012-2015 Digital Bazaar, Inc.
  9. *
  10. * Currently this implementation only supports ContentType of EnvelopedData,
  11. * EncryptedData, or SignedData at the root level. The top level elements may
  12. * contain only a ContentInfo of ContentType Data, i.e. plain data. Further
  13. * nesting is not (yet) supported.
  14. *
  15. * The Forge validators for PKCS #7's ASN.1 structures are available from
  16. * a separate file pkcs7asn1.js, since those are referenced from other
  17. * PKCS standards like PKCS #12.
  18. */
  19. var forge = require('./forge');
  20. require('./aes');
  21. require('./asn1');
  22. require('./des');
  23. require('./oids');
  24. require('./pem');
  25. require('./pkcs7asn1');
  26. require('./random');
  27. require('./util');
  28. require('./x509');
  29. // shortcut for ASN.1 API
  30. var asn1 = forge.asn1;
  31. // shortcut for PKCS#7 API
  32. var p7 = module.exports = forge.pkcs7 = forge.pkcs7 || {};
  33. /**
  34. * Converts a PKCS#7 message from PEM format.
  35. *
  36. * @param pem the PEM-formatted PKCS#7 message.
  37. *
  38. * @return the PKCS#7 message.
  39. */
  40. p7.messageFromPem = function(pem) {
  41. var msg = forge.pem.decode(pem)[0];
  42. if(msg.type !== 'PKCS7') {
  43. var error = new Error('Could not convert PKCS#7 message from PEM; PEM ' +
  44. 'header type is not "PKCS#7".');
  45. error.headerType = msg.type;
  46. throw error;
  47. }
  48. if(msg.procType && msg.procType.type === 'ENCRYPTED') {
  49. throw new Error('Could not convert PKCS#7 message from PEM; PEM is encrypted.');
  50. }
  51. // convert DER to ASN.1 object
  52. var obj = asn1.fromDer(msg.body);
  53. return p7.messageFromAsn1(obj);
  54. };
  55. /**
  56. * Converts a PKCS#7 message to PEM format.
  57. *
  58. * @param msg The PKCS#7 message object
  59. * @param maxline The maximum characters per line, defaults to 64.
  60. *
  61. * @return The PEM-formatted PKCS#7 message.
  62. */
  63. p7.messageToPem = function(msg, maxline) {
  64. // convert to ASN.1, then DER, then PEM-encode
  65. var pemObj = {
  66. type: 'PKCS7',
  67. body: asn1.toDer(msg.toAsn1()).getBytes()
  68. };
  69. return forge.pem.encode(pemObj, {maxline: maxline});
  70. };
  71. /**
  72. * Converts a PKCS#7 message from an ASN.1 object.
  73. *
  74. * @param obj the ASN.1 representation of a ContentInfo.
  75. *
  76. * @return the PKCS#7 message.
  77. */
  78. p7.messageFromAsn1 = function(obj) {
  79. // validate root level ContentInfo and capture data
  80. var capture = {};
  81. var errors = [];
  82. if(!asn1.validate(obj, p7.asn1.contentInfoValidator, capture, errors)) {
  83. var error = new Error('Cannot read PKCS#7 message. ' +
  84. 'ASN.1 object is not an PKCS#7 ContentInfo.');
  85. error.errors = errors;
  86. throw error;
  87. }
  88. var contentType = asn1.derToOid(capture.contentType);
  89. var msg;
  90. switch(contentType) {
  91. case forge.pki.oids.envelopedData:
  92. msg = p7.createEnvelopedData();
  93. break;
  94. case forge.pki.oids.encryptedData:
  95. msg = p7.createEncryptedData();
  96. break;
  97. case forge.pki.oids.signedData:
  98. msg = p7.createSignedData();
  99. break;
  100. default:
  101. throw new Error('Cannot read PKCS#7 message. ContentType with OID ' +
  102. contentType + ' is not (yet) supported.');
  103. }
  104. msg.fromAsn1(capture.content.value[0]);
  105. return msg;
  106. };
  107. p7.createSignedData = function() {
  108. var msg = null;
  109. msg = {
  110. type: forge.pki.oids.signedData,
  111. version: 1,
  112. certificates: [],
  113. crls: [],
  114. // TODO: add json-formatted signer stuff here?
  115. signers: [],
  116. // populated during sign()
  117. digestAlgorithmIdentifiers: [],
  118. contentInfo: null,
  119. signerInfos: [],
  120. fromAsn1: function(obj) {
  121. // validate SignedData content block and capture data.
  122. _fromAsn1(msg, obj, p7.asn1.signedDataValidator);
  123. msg.certificates = [];
  124. msg.crls = [];
  125. msg.digestAlgorithmIdentifiers = [];
  126. msg.contentInfo = null;
  127. msg.signerInfos = [];
  128. if(msg.rawCapture.certificates) {
  129. var certs = msg.rawCapture.certificates.value;
  130. for(var i = 0; i < certs.length; ++i) {
  131. msg.certificates.push(forge.pki.certificateFromAsn1(certs[i]));
  132. }
  133. }
  134. // TODO: parse crls
  135. },
  136. toAsn1: function() {
  137. // degenerate case with no content
  138. if(!msg.contentInfo) {
  139. msg.sign();
  140. }
  141. var certs = [];
  142. for(var i = 0; i < msg.certificates.length; ++i) {
  143. certs.push(forge.pki.certificateToAsn1(msg.certificates[i]));
  144. }
  145. var crls = [];
  146. // TODO: implement CRLs
  147. // [0] SignedData
  148. var signedData = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
  149. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  150. // Version
  151. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  152. asn1.integerToDer(msg.version).getBytes()),
  153. // DigestAlgorithmIdentifiers
  154. asn1.create(
  155. asn1.Class.UNIVERSAL, asn1.Type.SET, true,
  156. msg.digestAlgorithmIdentifiers),
  157. // ContentInfo
  158. msg.contentInfo
  159. ])
  160. ]);
  161. if(certs.length > 0) {
  162. // [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL
  163. signedData.value[0].value.push(
  164. asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, certs));
  165. }
  166. if(crls.length > 0) {
  167. // [1] IMPLICIT CertificateRevocationLists OPTIONAL
  168. signedData.value[0].value.push(
  169. asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, crls));
  170. }
  171. // SignerInfos
  172. signedData.value[0].value.push(
  173. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true,
  174. msg.signerInfos));
  175. // ContentInfo
  176. return asn1.create(
  177. asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  178. // ContentType
  179. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  180. asn1.oidToDer(msg.type).getBytes()),
  181. // [0] SignedData
  182. signedData
  183. ]);
  184. },
  185. /**
  186. * Add (another) entity to list of signers.
  187. *
  188. * Note: If authenticatedAttributes are provided, then, per RFC 2315,
  189. * they must include at least two attributes: content type and
  190. * message digest. The message digest attribute value will be
  191. * auto-calculated during signing and will be ignored if provided.
  192. *
  193. * Here's an example of providing these two attributes:
  194. *
  195. * forge.pkcs7.createSignedData();
  196. * p7.addSigner({
  197. * issuer: cert.issuer.attributes,
  198. * serialNumber: cert.serialNumber,
  199. * key: privateKey,
  200. * digestAlgorithm: forge.pki.oids.sha1,
  201. * authenticatedAttributes: [{
  202. * type: forge.pki.oids.contentType,
  203. * value: forge.pki.oids.data
  204. * }, {
  205. * type: forge.pki.oids.messageDigest
  206. * }]
  207. * });
  208. *
  209. * TODO: Support [subjectKeyIdentifier] as signer's ID.
  210. *
  211. * @param signer the signer information:
  212. * key the signer's private key.
  213. * [certificate] a certificate containing the public key
  214. * associated with the signer's private key; use this option as
  215. * an alternative to specifying signer.issuer and
  216. * signer.serialNumber.
  217. * [issuer] the issuer attributes (eg: cert.issuer.attributes).
  218. * [serialNumber] the signer's certificate's serial number in
  219. * hexadecimal (eg: cert.serialNumber).
  220. * [digestAlgorithm] the message digest OID, as a string, to use
  221. * (eg: forge.pki.oids.sha1).
  222. * [authenticatedAttributes] an optional array of attributes
  223. * to also sign along with the content.
  224. */
  225. addSigner: function(signer) {
  226. var issuer = signer.issuer;
  227. var serialNumber = signer.serialNumber;
  228. if(signer.certificate) {
  229. var cert = signer.certificate;
  230. if(typeof cert === 'string') {
  231. cert = forge.pki.certificateFromPem(cert);
  232. }
  233. issuer = cert.issuer.attributes;
  234. serialNumber = cert.serialNumber;
  235. }
  236. var key = signer.key;
  237. if(!key) {
  238. throw new Error(
  239. 'Could not add PKCS#7 signer; no private key specified.');
  240. }
  241. if(typeof key === 'string') {
  242. key = forge.pki.privateKeyFromPem(key);
  243. }
  244. // ensure OID known for digest algorithm
  245. var digestAlgorithm = signer.digestAlgorithm || forge.pki.oids.sha1;
  246. switch(digestAlgorithm) {
  247. case forge.pki.oids.sha1:
  248. case forge.pki.oids.sha256:
  249. case forge.pki.oids.sha384:
  250. case forge.pki.oids.sha512:
  251. case forge.pki.oids.md5:
  252. break;
  253. default:
  254. throw new Error(
  255. 'Could not add PKCS#7 signer; unknown message digest algorithm: ' +
  256. digestAlgorithm);
  257. }
  258. // if authenticatedAttributes is present, then the attributes
  259. // must contain at least PKCS #9 content-type and message-digest
  260. var authenticatedAttributes = signer.authenticatedAttributes || [];
  261. if(authenticatedAttributes.length > 0) {
  262. var contentType = false;
  263. var messageDigest = false;
  264. for(var i = 0; i < authenticatedAttributes.length; ++i) {
  265. var attr = authenticatedAttributes[i];
  266. if(!contentType && attr.type === forge.pki.oids.contentType) {
  267. contentType = true;
  268. if(messageDigest) {
  269. break;
  270. }
  271. continue;
  272. }
  273. if(!messageDigest && attr.type === forge.pki.oids.messageDigest) {
  274. messageDigest = true;
  275. if(contentType) {
  276. break;
  277. }
  278. continue;
  279. }
  280. }
  281. if(!contentType || !messageDigest) {
  282. throw new Error('Invalid signer.authenticatedAttributes. If ' +
  283. 'signer.authenticatedAttributes is specified, then it must ' +
  284. 'contain at least two attributes, PKCS #9 content-type and ' +
  285. 'PKCS #9 message-digest.');
  286. }
  287. }
  288. msg.signers.push({
  289. key: key,
  290. version: 1,
  291. issuer: issuer,
  292. serialNumber: serialNumber,
  293. digestAlgorithm: digestAlgorithm,
  294. signatureAlgorithm: forge.pki.oids.rsaEncryption,
  295. signature: null,
  296. authenticatedAttributes: authenticatedAttributes,
  297. unauthenticatedAttributes: []
  298. });
  299. },
  300. /**
  301. * Signs the content.
  302. */
  303. sign: function() {
  304. // auto-generate content info
  305. if(typeof msg.content !== 'object' || msg.contentInfo === null) {
  306. // use Data ContentInfo
  307. msg.contentInfo = asn1.create(
  308. asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  309. // ContentType
  310. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  311. asn1.oidToDer(forge.pki.oids.data).getBytes())
  312. ]);
  313. // add actual content, if present
  314. if('content' in msg) {
  315. var content;
  316. if(msg.content instanceof forge.util.ByteBuffer) {
  317. content = msg.content.bytes();
  318. } else if(typeof msg.content === 'string') {
  319. content = forge.util.encodeUtf8(msg.content);
  320. }
  321. msg.contentInfo.value.push(
  322. // [0] EXPLICIT content
  323. asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
  324. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,
  325. content)
  326. ]));
  327. }
  328. }
  329. // no signers, return early (degenerate case for certificate container)
  330. if(msg.signers.length === 0) {
  331. return;
  332. }
  333. // generate digest algorithm identifiers
  334. var mds = addDigestAlgorithmIds();
  335. // generate signerInfos
  336. addSignerInfos(mds);
  337. },
  338. verify: function() {
  339. throw new Error('PKCS#7 signature verification not yet implemented.');
  340. },
  341. /**
  342. * Add a certificate.
  343. *
  344. * @param cert the certificate to add.
  345. */
  346. addCertificate: function(cert) {
  347. // convert from PEM
  348. if(typeof cert === 'string') {
  349. cert = forge.pki.certificateFromPem(cert);
  350. }
  351. msg.certificates.push(cert);
  352. },
  353. /**
  354. * Add a certificate revokation list.
  355. *
  356. * @param crl the certificate revokation list to add.
  357. */
  358. addCertificateRevokationList: function(crl) {
  359. throw new Error('PKCS#7 CRL support not yet implemented.');
  360. }
  361. };
  362. return msg;
  363. function addDigestAlgorithmIds() {
  364. var mds = {};
  365. for(var i = 0; i < msg.signers.length; ++i) {
  366. var signer = msg.signers[i];
  367. var oid = signer.digestAlgorithm;
  368. if(!(oid in mds)) {
  369. // content digest
  370. mds[oid] = forge.md[forge.pki.oids[oid]].create();
  371. }
  372. if(signer.authenticatedAttributes.length === 0) {
  373. // no custom attributes to digest; use content message digest
  374. signer.md = mds[oid];
  375. } else {
  376. // custom attributes to be digested; use own message digest
  377. // TODO: optimize to just copy message digest state if that
  378. // feature is ever supported with message digests
  379. signer.md = forge.md[forge.pki.oids[oid]].create();
  380. }
  381. }
  382. // add unique digest algorithm identifiers
  383. msg.digestAlgorithmIdentifiers = [];
  384. for(var oid in mds) {
  385. msg.digestAlgorithmIdentifiers.push(
  386. // AlgorithmIdentifier
  387. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  388. // algorithm
  389. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  390. asn1.oidToDer(oid).getBytes()),
  391. // parameters (null)
  392. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')
  393. ]));
  394. }
  395. return mds;
  396. }
  397. function addSignerInfos(mds) {
  398. // Note: ContentInfo is a SEQUENCE with 2 values, second value is
  399. // the content field and is optional for a ContentInfo but required here
  400. // since signers are present
  401. if(msg.contentInfo.value.length < 2) {
  402. throw new Error(
  403. 'Could not sign PKCS#7 message; there is no content to sign.');
  404. }
  405. // get ContentInfo content type
  406. var contentType = asn1.derToOid(msg.contentInfo.value[0].value);
  407. // get ContentInfo content
  408. var content = msg.contentInfo.value[1];
  409. // skip [0] EXPLICIT content wrapper
  410. content = content.value[0];
  411. // serialize content
  412. var bytes = asn1.toDer(content);
  413. // skip identifier and length per RFC 2315 9.3
  414. // skip identifier (1 byte)
  415. bytes.getByte();
  416. // read and discard length bytes
  417. asn1.getBerValueLength(bytes);
  418. bytes = bytes.getBytes();
  419. // digest content DER value bytes
  420. for(var oid in mds) {
  421. mds[oid].start().update(bytes);
  422. }
  423. // sign content
  424. var signingTime = new Date();
  425. for(var i = 0; i < msg.signers.length; ++i) {
  426. var signer = msg.signers[i];
  427. if(signer.authenticatedAttributes.length === 0) {
  428. // if ContentInfo content type is not "Data", then
  429. // authenticatedAttributes must be present per RFC 2315
  430. if(contentType !== forge.pki.oids.data) {
  431. throw new Error(
  432. 'Invalid signer; authenticatedAttributes must be present ' +
  433. 'when the ContentInfo content type is not PKCS#7 Data.');
  434. }
  435. } else {
  436. // process authenticated attributes
  437. // [0] IMPLICIT
  438. signer.authenticatedAttributesAsn1 = asn1.create(
  439. asn1.Class.CONTEXT_SPECIFIC, 0, true, []);
  440. // per RFC 2315, attributes are to be digested using a SET container
  441. // not the above [0] IMPLICIT container
  442. var attrsAsn1 = asn1.create(
  443. asn1.Class.UNIVERSAL, asn1.Type.SET, true, []);
  444. for(var ai = 0; ai < signer.authenticatedAttributes.length; ++ai) {
  445. var attr = signer.authenticatedAttributes[ai];
  446. if(attr.type === forge.pki.oids.messageDigest) {
  447. // use content message digest as value
  448. attr.value = mds[signer.digestAlgorithm].digest();
  449. } else if(attr.type === forge.pki.oids.signingTime) {
  450. // auto-populate signing time if not already set
  451. if(!attr.value) {
  452. attr.value = signingTime;
  453. }
  454. }
  455. // convert to ASN.1 and push onto Attributes SET (for signing) and
  456. // onto authenticatedAttributesAsn1 to complete SignedData ASN.1
  457. // TODO: optimize away duplication
  458. attrsAsn1.value.push(_attributeToAsn1(attr));
  459. signer.authenticatedAttributesAsn1.value.push(_attributeToAsn1(attr));
  460. }
  461. // DER-serialize and digest SET OF attributes only
  462. bytes = asn1.toDer(attrsAsn1).getBytes();
  463. signer.md.start().update(bytes);
  464. }
  465. // sign digest
  466. signer.signature = signer.key.sign(signer.md, 'RSASSA-PKCS1-V1_5');
  467. }
  468. // add signer info
  469. msg.signerInfos = _signersToAsn1(msg.signers);
  470. }
  471. };
  472. /**
  473. * Creates an empty PKCS#7 message of type EncryptedData.
  474. *
  475. * @return the message.
  476. */
  477. p7.createEncryptedData = function() {
  478. var msg = null;
  479. msg = {
  480. type: forge.pki.oids.encryptedData,
  481. version: 0,
  482. encryptedContent: {
  483. algorithm: forge.pki.oids['aes256-CBC']
  484. },
  485. /**
  486. * Reads an EncryptedData content block (in ASN.1 format)
  487. *
  488. * @param obj The ASN.1 representation of the EncryptedData content block
  489. */
  490. fromAsn1: function(obj) {
  491. // Validate EncryptedData content block and capture data.
  492. _fromAsn1(msg, obj, p7.asn1.encryptedDataValidator);
  493. },
  494. /**
  495. * Decrypt encrypted content
  496. *
  497. * @param key The (symmetric) key as a byte buffer
  498. */
  499. decrypt: function(key) {
  500. if(key !== undefined) {
  501. msg.encryptedContent.key = key;
  502. }
  503. _decryptContent(msg);
  504. }
  505. };
  506. return msg;
  507. };
  508. /**
  509. * Creates an empty PKCS#7 message of type EnvelopedData.
  510. *
  511. * @return the message.
  512. */
  513. p7.createEnvelopedData = function() {
  514. var msg = null;
  515. msg = {
  516. type: forge.pki.oids.envelopedData,
  517. version: 0,
  518. recipients: [],
  519. encryptedContent: {
  520. algorithm: forge.pki.oids['aes256-CBC']
  521. },
  522. /**
  523. * Reads an EnvelopedData content block (in ASN.1 format)
  524. *
  525. * @param obj the ASN.1 representation of the EnvelopedData content block.
  526. */
  527. fromAsn1: function(obj) {
  528. // validate EnvelopedData content block and capture data
  529. var capture = _fromAsn1(msg, obj, p7.asn1.envelopedDataValidator);
  530. msg.recipients = _recipientsFromAsn1(capture.recipientInfos.value);
  531. },
  532. toAsn1: function() {
  533. // ContentInfo
  534. return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  535. // ContentType
  536. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  537. asn1.oidToDer(msg.type).getBytes()),
  538. // [0] EnvelopedData
  539. asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
  540. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  541. // Version
  542. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  543. asn1.integerToDer(msg.version).getBytes()),
  544. // RecipientInfos
  545. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true,
  546. _recipientsToAsn1(msg.recipients)),
  547. // EncryptedContentInfo
  548. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true,
  549. _encryptedContentToAsn1(msg.encryptedContent))
  550. ])
  551. ])
  552. ]);
  553. },
  554. /**
  555. * Find recipient by X.509 certificate's issuer.
  556. *
  557. * @param cert the certificate with the issuer to look for.
  558. *
  559. * @return the recipient object.
  560. */
  561. findRecipient: function(cert) {
  562. var sAttr = cert.issuer.attributes;
  563. for(var i = 0; i < msg.recipients.length; ++i) {
  564. var r = msg.recipients[i];
  565. var rAttr = r.issuer;
  566. if(r.serialNumber !== cert.serialNumber) {
  567. continue;
  568. }
  569. if(rAttr.length !== sAttr.length) {
  570. continue;
  571. }
  572. var match = true;
  573. for(var j = 0; j < sAttr.length; ++j) {
  574. if(rAttr[j].type !== sAttr[j].type ||
  575. rAttr[j].value !== sAttr[j].value) {
  576. match = false;
  577. break;
  578. }
  579. }
  580. if(match) {
  581. return r;
  582. }
  583. }
  584. return null;
  585. },
  586. /**
  587. * Decrypt enveloped content
  588. *
  589. * @param recipient The recipient object related to the private key
  590. * @param privKey The (RSA) private key object
  591. */
  592. decrypt: function(recipient, privKey) {
  593. if(msg.encryptedContent.key === undefined && recipient !== undefined &&
  594. privKey !== undefined) {
  595. switch(recipient.encryptedContent.algorithm) {
  596. case forge.pki.oids.rsaEncryption:
  597. case forge.pki.oids.desCBC:
  598. var key = privKey.decrypt(recipient.encryptedContent.content);
  599. msg.encryptedContent.key = forge.util.createBuffer(key);
  600. break;
  601. default:
  602. throw new Error('Unsupported asymmetric cipher, ' +
  603. 'OID ' + recipient.encryptedContent.algorithm);
  604. }
  605. }
  606. _decryptContent(msg);
  607. },
  608. /**
  609. * Add (another) entity to list of recipients.
  610. *
  611. * @param cert The certificate of the entity to add.
  612. */
  613. addRecipient: function(cert) {
  614. msg.recipients.push({
  615. version: 0,
  616. issuer: cert.issuer.attributes,
  617. serialNumber: cert.serialNumber,
  618. encryptedContent: {
  619. // We simply assume rsaEncryption here, since forge.pki only
  620. // supports RSA so far. If the PKI module supports other
  621. // ciphers one day, we need to modify this one as well.
  622. algorithm: forge.pki.oids.rsaEncryption,
  623. key: cert.publicKey
  624. }
  625. });
  626. },
  627. /**
  628. * Encrypt enveloped content.
  629. *
  630. * This function supports two optional arguments, cipher and key, which
  631. * can be used to influence symmetric encryption. Unless cipher is
  632. * provided, the cipher specified in encryptedContent.algorithm is used
  633. * (defaults to AES-256-CBC). If no key is provided, encryptedContent.key
  634. * is (re-)used. If that one's not set, a random key will be generated
  635. * automatically.
  636. *
  637. * @param [key] The key to be used for symmetric encryption.
  638. * @param [cipher] The OID of the symmetric cipher to use.
  639. */
  640. encrypt: function(key, cipher) {
  641. // Part 1: Symmetric encryption
  642. if(msg.encryptedContent.content === undefined) {
  643. cipher = cipher || msg.encryptedContent.algorithm;
  644. key = key || msg.encryptedContent.key;
  645. var keyLen, ivLen, ciphFn;
  646. switch(cipher) {
  647. case forge.pki.oids['aes128-CBC']:
  648. keyLen = 16;
  649. ivLen = 16;
  650. ciphFn = forge.aes.createEncryptionCipher;
  651. break;
  652. case forge.pki.oids['aes192-CBC']:
  653. keyLen = 24;
  654. ivLen = 16;
  655. ciphFn = forge.aes.createEncryptionCipher;
  656. break;
  657. case forge.pki.oids['aes256-CBC']:
  658. keyLen = 32;
  659. ivLen = 16;
  660. ciphFn = forge.aes.createEncryptionCipher;
  661. break;
  662. case forge.pki.oids['des-EDE3-CBC']:
  663. keyLen = 24;
  664. ivLen = 8;
  665. ciphFn = forge.des.createEncryptionCipher;
  666. break;
  667. default:
  668. throw new Error('Unsupported symmetric cipher, OID ' + cipher);
  669. }
  670. if(key === undefined) {
  671. key = forge.util.createBuffer(forge.random.getBytes(keyLen));
  672. } else if(key.length() != keyLen) {
  673. throw new Error('Symmetric key has wrong length; ' +
  674. 'got ' + key.length() + ' bytes, expected ' + keyLen + '.');
  675. }
  676. // Keep a copy of the key & IV in the object, so the caller can
  677. // use it for whatever reason.
  678. msg.encryptedContent.algorithm = cipher;
  679. msg.encryptedContent.key = key;
  680. msg.encryptedContent.parameter = forge.util.createBuffer(
  681. forge.random.getBytes(ivLen));
  682. var ciph = ciphFn(key);
  683. ciph.start(msg.encryptedContent.parameter.copy());
  684. ciph.update(msg.content);
  685. // The finish function does PKCS#7 padding by default, therefore
  686. // no action required by us.
  687. if(!ciph.finish()) {
  688. throw new Error('Symmetric encryption failed.');
  689. }
  690. msg.encryptedContent.content = ciph.output;
  691. }
  692. // Part 2: asymmetric encryption for each recipient
  693. for(var i = 0; i < msg.recipients.length; ++i) {
  694. var recipient = msg.recipients[i];
  695. // Nothing to do, encryption already done.
  696. if(recipient.encryptedContent.content !== undefined) {
  697. continue;
  698. }
  699. switch(recipient.encryptedContent.algorithm) {
  700. case forge.pki.oids.rsaEncryption:
  701. recipient.encryptedContent.content =
  702. recipient.encryptedContent.key.encrypt(
  703. msg.encryptedContent.key.data);
  704. break;
  705. default:
  706. throw new Error('Unsupported asymmetric cipher, OID ' +
  707. recipient.encryptedContent.algorithm);
  708. }
  709. }
  710. }
  711. };
  712. return msg;
  713. };
  714. /**
  715. * Converts a single recipient from an ASN.1 object.
  716. *
  717. * @param obj the ASN.1 RecipientInfo.
  718. *
  719. * @return the recipient object.
  720. */
  721. function _recipientFromAsn1(obj) {
  722. // validate EnvelopedData content block and capture data
  723. var capture = {};
  724. var errors = [];
  725. if(!asn1.validate(obj, p7.asn1.recipientInfoValidator, capture, errors)) {
  726. var error = new Error('Cannot read PKCS#7 RecipientInfo. ' +
  727. 'ASN.1 object is not an PKCS#7 RecipientInfo.');
  728. error.errors = errors;
  729. throw error;
  730. }
  731. return {
  732. version: capture.version.charCodeAt(0),
  733. issuer: forge.pki.RDNAttributesAsArray(capture.issuer),
  734. serialNumber: forge.util.createBuffer(capture.serial).toHex(),
  735. encryptedContent: {
  736. algorithm: asn1.derToOid(capture.encAlgorithm),
  737. parameter: capture.encParameter.value,
  738. content: capture.encKey
  739. }
  740. };
  741. }
  742. /**
  743. * Converts a single recipient object to an ASN.1 object.
  744. *
  745. * @param obj the recipient object.
  746. *
  747. * @return the ASN.1 RecipientInfo.
  748. */
  749. function _recipientToAsn1(obj) {
  750. return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  751. // Version
  752. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  753. asn1.integerToDer(obj.version).getBytes()),
  754. // IssuerAndSerialNumber
  755. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  756. // Name
  757. forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}),
  758. // Serial
  759. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  760. forge.util.hexToBytes(obj.serialNumber))
  761. ]),
  762. // KeyEncryptionAlgorithmIdentifier
  763. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  764. // Algorithm
  765. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  766. asn1.oidToDer(obj.encryptedContent.algorithm).getBytes()),
  767. // Parameter, force NULL, only RSA supported for now.
  768. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')
  769. ]),
  770. // EncryptedKey
  771. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,
  772. obj.encryptedContent.content)
  773. ]);
  774. }
  775. /**
  776. * Map a set of RecipientInfo ASN.1 objects to recipient objects.
  777. *
  778. * @param infos an array of ASN.1 representations RecipientInfo (i.e. SET OF).
  779. *
  780. * @return an array of recipient objects.
  781. */
  782. function _recipientsFromAsn1(infos) {
  783. var ret = [];
  784. for(var i = 0; i < infos.length; ++i) {
  785. ret.push(_recipientFromAsn1(infos[i]));
  786. }
  787. return ret;
  788. }
  789. /**
  790. * Map an array of recipient objects to ASN.1 RecipientInfo objects.
  791. *
  792. * @param recipients an array of recipientInfo objects.
  793. *
  794. * @return an array of ASN.1 RecipientInfos.
  795. */
  796. function _recipientsToAsn1(recipients) {
  797. var ret = [];
  798. for(var i = 0; i < recipients.length; ++i) {
  799. ret.push(_recipientToAsn1(recipients[i]));
  800. }
  801. return ret;
  802. }
  803. /**
  804. * Converts a single signer from an ASN.1 object.
  805. *
  806. * @param obj the ASN.1 representation of a SignerInfo.
  807. *
  808. * @return the signer object.
  809. */
  810. function _signerFromAsn1(obj) {
  811. // validate EnvelopedData content block and capture data
  812. var capture = {};
  813. var errors = [];
  814. if(!asn1.validate(obj, p7.asn1.signerInfoValidator, capture, errors)) {
  815. var error = new Error('Cannot read PKCS#7 SignerInfo. ' +
  816. 'ASN.1 object is not an PKCS#7 SignerInfo.');
  817. error.errors = errors;
  818. throw error;
  819. }
  820. var rval = {
  821. version: capture.version.charCodeAt(0),
  822. issuer: forge.pki.RDNAttributesAsArray(capture.issuer),
  823. serialNumber: forge.util.createBuffer(capture.serial).toHex(),
  824. digestAlgorithm: asn1.derToOid(capture.digestAlgorithm),
  825. signatureAlgorithm: asn1.derToOid(capture.signatureAlgorithm),
  826. signature: capture.signature,
  827. authenticatedAttributes: [],
  828. unauthenticatedAttributes: []
  829. };
  830. // TODO: convert attributes
  831. var authenticatedAttributes = capture.authenticatedAttributes || [];
  832. var unauthenticatedAttributes = capture.unauthenticatedAttributes || [];
  833. return rval;
  834. }
  835. /**
  836. * Converts a single signerInfo object to an ASN.1 object.
  837. *
  838. * @param obj the signerInfo object.
  839. *
  840. * @return the ASN.1 representation of a SignerInfo.
  841. */
  842. function _signerToAsn1(obj) {
  843. // SignerInfo
  844. var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  845. // version
  846. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  847. asn1.integerToDer(obj.version).getBytes()),
  848. // issuerAndSerialNumber
  849. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  850. // name
  851. forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}),
  852. // serial
  853. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  854. forge.util.hexToBytes(obj.serialNumber))
  855. ]),
  856. // digestAlgorithm
  857. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  858. // algorithm
  859. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  860. asn1.oidToDer(obj.digestAlgorithm).getBytes()),
  861. // parameters (null)
  862. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')
  863. ])
  864. ]);
  865. // authenticatedAttributes (OPTIONAL)
  866. if(obj.authenticatedAttributesAsn1) {
  867. // add ASN.1 previously generated during signing
  868. rval.value.push(obj.authenticatedAttributesAsn1);
  869. }
  870. // digestEncryptionAlgorithm
  871. rval.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  872. // algorithm
  873. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  874. asn1.oidToDer(obj.signatureAlgorithm).getBytes()),
  875. // parameters (null)
  876. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')
  877. ]));
  878. // encryptedDigest
  879. rval.value.push(asn1.create(
  880. asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, obj.signature));
  881. // unauthenticatedAttributes (OPTIONAL)
  882. if(obj.unauthenticatedAttributes.length > 0) {
  883. // [1] IMPLICIT
  884. var attrsAsn1 = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, []);
  885. for(var i = 0; i < obj.unauthenticatedAttributes.length; ++i) {
  886. var attr = obj.unauthenticatedAttributes[i];
  887. attrsAsn1.values.push(_attributeToAsn1(attr));
  888. }
  889. rval.value.push(attrsAsn1);
  890. }
  891. return rval;
  892. }
  893. /**
  894. * Map a set of SignerInfo ASN.1 objects to an array of signer objects.
  895. *
  896. * @param signerInfoAsn1s an array of ASN.1 SignerInfos (i.e. SET OF).
  897. *
  898. * @return an array of signers objects.
  899. */
  900. function _signersFromAsn1(signerInfoAsn1s) {
  901. var ret = [];
  902. for(var i = 0; i < signerInfoAsn1s.length; ++i) {
  903. ret.push(_signerFromAsn1(signerInfoAsn1s[i]));
  904. }
  905. return ret;
  906. }
  907. /**
  908. * Map an array of signer objects to ASN.1 objects.
  909. *
  910. * @param signers an array of signer objects.
  911. *
  912. * @return an array of ASN.1 SignerInfos.
  913. */
  914. function _signersToAsn1(signers) {
  915. var ret = [];
  916. for(var i = 0; i < signers.length; ++i) {
  917. ret.push(_signerToAsn1(signers[i]));
  918. }
  919. return ret;
  920. }
  921. /**
  922. * Convert an attribute object to an ASN.1 Attribute.
  923. *
  924. * @param attr the attribute object.
  925. *
  926. * @return the ASN.1 Attribute.
  927. */
  928. function _attributeToAsn1(attr) {
  929. var value;
  930. // TODO: generalize to support more attributes
  931. if(attr.type === forge.pki.oids.contentType) {
  932. value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  933. asn1.oidToDer(attr.value).getBytes());
  934. } else if(attr.type === forge.pki.oids.messageDigest) {
  935. value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,
  936. attr.value.bytes());
  937. } else if(attr.type === forge.pki.oids.signingTime) {
  938. /* Note per RFC 2985: Dates between 1 January 1950 and 31 December 2049
  939. (inclusive) MUST be encoded as UTCTime. Any dates with year values
  940. before 1950 or after 2049 MUST be encoded as GeneralizedTime. [Further,]
  941. UTCTime values MUST be expressed in Greenwich Mean Time (Zulu) and MUST
  942. include seconds (i.e., times are YYMMDDHHMMSSZ), even where the
  943. number of seconds is zero. Midnight (GMT) must be represented as
  944. "YYMMDD000000Z". */
  945. // TODO: make these module-level constants
  946. var jan_1_1950 = new Date('1950-01-01T00:00:00Z');
  947. var jan_1_2050 = new Date('2050-01-01T00:00:00Z');
  948. var date = attr.value;
  949. if(typeof date === 'string') {
  950. // try to parse date
  951. var timestamp = Date.parse(date);
  952. if(!isNaN(timestamp)) {
  953. date = new Date(timestamp);
  954. } else if(date.length === 13) {
  955. // YYMMDDHHMMSSZ (13 chars for UTCTime)
  956. date = asn1.utcTimeToDate(date);
  957. } else {
  958. // assume generalized time
  959. date = asn1.generalizedTimeToDate(date);
  960. }
  961. }
  962. if(date >= jan_1_1950 && date < jan_1_2050) {
  963. value = asn1.create(
  964. asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false,
  965. asn1.dateToUtcTime(date));
  966. } else {
  967. value = asn1.create(
  968. asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false,
  969. asn1.dateToGeneralizedTime(date));
  970. }
  971. }
  972. // TODO: expose as common API call
  973. // create a RelativeDistinguishedName set
  974. // each value in the set is an AttributeTypeAndValue first
  975. // containing the type (an OID) and second the value
  976. return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  977. // AttributeType
  978. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  979. asn1.oidToDer(attr.type).getBytes()),
  980. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [
  981. // AttributeValue
  982. value
  983. ])
  984. ]);
  985. }
  986. /**
  987. * Map messages encrypted content to ASN.1 objects.
  988. *
  989. * @param ec The encryptedContent object of the message.
  990. *
  991. * @return ASN.1 representation of the encryptedContent object (SEQUENCE).
  992. */
  993. function _encryptedContentToAsn1(ec) {
  994. return [
  995. // ContentType, always Data for the moment
  996. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  997. asn1.oidToDer(forge.pki.oids.data).getBytes()),
  998. // ContentEncryptionAlgorithmIdentifier
  999. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  1000. // Algorithm
  1001. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  1002. asn1.oidToDer(ec.algorithm).getBytes()),
  1003. // Parameters (IV)
  1004. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,
  1005. ec.parameter.getBytes())
  1006. ]),
  1007. // [0] EncryptedContent
  1008. asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
  1009. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,
  1010. ec.content.getBytes())
  1011. ])
  1012. ];
  1013. }
  1014. /**
  1015. * Reads the "common part" of an PKCS#7 content block (in ASN.1 format)
  1016. *
  1017. * This function reads the "common part" of the PKCS#7 content blocks
  1018. * EncryptedData and EnvelopedData, i.e. version number and symmetrically
  1019. * encrypted content block.
  1020. *
  1021. * The result of the ASN.1 validate and capture process is returned
  1022. * to allow the caller to extract further data, e.g. the list of recipients
  1023. * in case of a EnvelopedData object.
  1024. *
  1025. * @param msg the PKCS#7 object to read the data to.
  1026. * @param obj the ASN.1 representation of the content block.
  1027. * @param validator the ASN.1 structure validator object to use.
  1028. *
  1029. * @return the value map captured by validator object.
  1030. */
  1031. function _fromAsn1(msg, obj, validator) {
  1032. var capture = {};
  1033. var errors = [];
  1034. if(!asn1.validate(obj, validator, capture, errors)) {
  1035. var error = new Error('Cannot read PKCS#7 message. ' +
  1036. 'ASN.1 object is not a supported PKCS#7 message.');
  1037. error.errors = error;
  1038. throw error;
  1039. }
  1040. // Check contentType, so far we only support (raw) Data.
  1041. var contentType = asn1.derToOid(capture.contentType);
  1042. if(contentType !== forge.pki.oids.data) {
  1043. throw new Error('Unsupported PKCS#7 message. ' +
  1044. 'Only wrapped ContentType Data supported.');
  1045. }
  1046. if(capture.encryptedContent) {
  1047. var content = '';
  1048. if(forge.util.isArray(capture.encryptedContent)) {
  1049. for(var i = 0; i < capture.encryptedContent.length; ++i) {
  1050. if(capture.encryptedContent[i].type !== asn1.Type.OCTETSTRING) {
  1051. throw new Error('Malformed PKCS#7 message, expecting encrypted ' +
  1052. 'content constructed of only OCTET STRING objects.');
  1053. }
  1054. content += capture.encryptedContent[i].value;
  1055. }
  1056. } else {
  1057. content = capture.encryptedContent;
  1058. }
  1059. msg.encryptedContent = {
  1060. algorithm: asn1.derToOid(capture.encAlgorithm),
  1061. parameter: forge.util.createBuffer(capture.encParameter.value),
  1062. content: forge.util.createBuffer(content)
  1063. };
  1064. }
  1065. if(capture.content) {
  1066. var content = '';
  1067. if(forge.util.isArray(capture.content)) {
  1068. for(var i = 0; i < capture.content.length; ++i) {
  1069. if(capture.content[i].type !== asn1.Type.OCTETSTRING) {
  1070. throw new Error('Malformed PKCS#7 message, expecting ' +
  1071. 'content constructed of only OCTET STRING objects.');
  1072. }
  1073. content += capture.content[i].value;
  1074. }
  1075. } else {
  1076. content = capture.content;
  1077. }
  1078. msg.content = forge.util.createBuffer(content);
  1079. }
  1080. msg.version = capture.version.charCodeAt(0);
  1081. msg.rawCapture = capture;
  1082. return capture;
  1083. }
  1084. /**
  1085. * Decrypt the symmetrically encrypted content block of the PKCS#7 message.
  1086. *
  1087. * Decryption is skipped in case the PKCS#7 message object already has a
  1088. * (decrypted) content attribute. The algorithm, key and cipher parameters
  1089. * (probably the iv) are taken from the encryptedContent attribute of the
  1090. * message object.
  1091. *
  1092. * @param The PKCS#7 message object.
  1093. */
  1094. function _decryptContent(msg) {
  1095. if(msg.encryptedContent.key === undefined) {
  1096. throw new Error('Symmetric key not available.');
  1097. }
  1098. if(msg.content === undefined) {
  1099. var ciph;
  1100. switch(msg.encryptedContent.algorithm) {
  1101. case forge.pki.oids['aes128-CBC']:
  1102. case forge.pki.oids['aes192-CBC']:
  1103. case forge.pki.oids['aes256-CBC']:
  1104. ciph = forge.aes.createDecryptionCipher(msg.encryptedContent.key);
  1105. break;
  1106. case forge.pki.oids['desCBC']:
  1107. case forge.pki.oids['des-EDE3-CBC']:
  1108. ciph = forge.des.createDecryptionCipher(msg.encryptedContent.key);
  1109. break;
  1110. default:
  1111. throw new Error('Unsupported symmetric cipher, OID ' +
  1112. msg.encryptedContent.algorithm);
  1113. }
  1114. ciph.start(msg.encryptedContent.parameter);
  1115. ciph.update(msg.encryptedContent.content);
  1116. if(!ciph.finish()) {
  1117. throw new Error('Symmetric decryption failed.');
  1118. }
  1119. msg.content = ciph.output;
  1120. }
  1121. }