pkcs7-modified.js 40 KB

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