You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1023 lines
30 KiB

4 years ago
  1. /**
  2. * Password-based encryption functions.
  3. *
  4. * @author Dave Longley
  5. * @author Stefan Siegl <stesie@brokenpipe.de>
  6. *
  7. * Copyright (c) 2010-2013 Digital Bazaar, Inc.
  8. * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>
  9. *
  10. * An EncryptedPrivateKeyInfo:
  11. *
  12. * EncryptedPrivateKeyInfo ::= SEQUENCE {
  13. * encryptionAlgorithm EncryptionAlgorithmIdentifier,
  14. * encryptedData EncryptedData }
  15. *
  16. * EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
  17. *
  18. * EncryptedData ::= OCTET STRING
  19. */
  20. var forge = require('./forge');
  21. require('./aes');
  22. require('./asn1');
  23. require('./des');
  24. require('./md');
  25. require('./oids');
  26. require('./pbkdf2');
  27. require('./pem');
  28. require('./random');
  29. require('./rc2');
  30. require('./rsa');
  31. require('./util');
  32. if(typeof BigInteger === 'undefined') {
  33. var BigInteger = forge.jsbn.BigInteger;
  34. }
  35. // shortcut for asn.1 API
  36. var asn1 = forge.asn1;
  37. /* Password-based encryption implementation. */
  38. var pki = forge.pki = forge.pki || {};
  39. module.exports = pki.pbe = forge.pbe = forge.pbe || {};
  40. var oids = pki.oids;
  41. // validator for an EncryptedPrivateKeyInfo structure
  42. // Note: Currently only works w/algorithm params
  43. var encryptedPrivateKeyValidator = {
  44. name: 'EncryptedPrivateKeyInfo',
  45. tagClass: asn1.Class.UNIVERSAL,
  46. type: asn1.Type.SEQUENCE,
  47. constructed: true,
  48. value: [{
  49. name: 'EncryptedPrivateKeyInfo.encryptionAlgorithm',
  50. tagClass: asn1.Class.UNIVERSAL,
  51. type: asn1.Type.SEQUENCE,
  52. constructed: true,
  53. value: [{
  54. name: 'AlgorithmIdentifier.algorithm',
  55. tagClass: asn1.Class.UNIVERSAL,
  56. type: asn1.Type.OID,
  57. constructed: false,
  58. capture: 'encryptionOid'
  59. }, {
  60. name: 'AlgorithmIdentifier.parameters',
  61. tagClass: asn1.Class.UNIVERSAL,
  62. type: asn1.Type.SEQUENCE,
  63. constructed: true,
  64. captureAsn1: 'encryptionParams'
  65. }]
  66. }, {
  67. // encryptedData
  68. name: 'EncryptedPrivateKeyInfo.encryptedData',
  69. tagClass: asn1.Class.UNIVERSAL,
  70. type: asn1.Type.OCTETSTRING,
  71. constructed: false,
  72. capture: 'encryptedData'
  73. }]
  74. };
  75. // validator for a PBES2Algorithms structure
  76. // Note: Currently only works w/PBKDF2 + AES encryption schemes
  77. var PBES2AlgorithmsValidator = {
  78. name: 'PBES2Algorithms',
  79. tagClass: asn1.Class.UNIVERSAL,
  80. type: asn1.Type.SEQUENCE,
  81. constructed: true,
  82. value: [{
  83. name: 'PBES2Algorithms.keyDerivationFunc',
  84. tagClass: asn1.Class.UNIVERSAL,
  85. type: asn1.Type.SEQUENCE,
  86. constructed: true,
  87. value: [{
  88. name: 'PBES2Algorithms.keyDerivationFunc.oid',
  89. tagClass: asn1.Class.UNIVERSAL,
  90. type: asn1.Type.OID,
  91. constructed: false,
  92. capture: 'kdfOid'
  93. }, {
  94. name: 'PBES2Algorithms.params',
  95. tagClass: asn1.Class.UNIVERSAL,
  96. type: asn1.Type.SEQUENCE,
  97. constructed: true,
  98. value: [{
  99. name: 'PBES2Algorithms.params.salt',
  100. tagClass: asn1.Class.UNIVERSAL,
  101. type: asn1.Type.OCTETSTRING,
  102. constructed: false,
  103. capture: 'kdfSalt'
  104. }, {
  105. name: 'PBES2Algorithms.params.iterationCount',
  106. tagClass: asn1.Class.UNIVERSAL,
  107. type: asn1.Type.INTEGER,
  108. constructed: false,
  109. capture: 'kdfIterationCount'
  110. }, {
  111. name: 'PBES2Algorithms.params.keyLength',
  112. tagClass: asn1.Class.UNIVERSAL,
  113. type: asn1.Type.INTEGER,
  114. constructed: false,
  115. optional: true,
  116. capture: 'keyLength'
  117. }, {
  118. // prf
  119. name: 'PBES2Algorithms.params.prf',
  120. tagClass: asn1.Class.UNIVERSAL,
  121. type: asn1.Type.SEQUENCE,
  122. constructed: true,
  123. optional: true,
  124. value: [{
  125. name: 'PBES2Algorithms.params.prf.algorithm',
  126. tagClass: asn1.Class.UNIVERSAL,
  127. type: asn1.Type.OID,
  128. constructed: false,
  129. capture: 'prfOid'
  130. }]
  131. }]
  132. }]
  133. }, {
  134. name: 'PBES2Algorithms.encryptionScheme',
  135. tagClass: asn1.Class.UNIVERSAL,
  136. type: asn1.Type.SEQUENCE,
  137. constructed: true,
  138. value: [{
  139. name: 'PBES2Algorithms.encryptionScheme.oid',
  140. tagClass: asn1.Class.UNIVERSAL,
  141. type: asn1.Type.OID,
  142. constructed: false,
  143. capture: 'encOid'
  144. }, {
  145. name: 'PBES2Algorithms.encryptionScheme.iv',
  146. tagClass: asn1.Class.UNIVERSAL,
  147. type: asn1.Type.OCTETSTRING,
  148. constructed: false,
  149. capture: 'encIv'
  150. }]
  151. }]
  152. };
  153. var pkcs12PbeParamsValidator = {
  154. name: 'pkcs-12PbeParams',
  155. tagClass: asn1.Class.UNIVERSAL,
  156. type: asn1.Type.SEQUENCE,
  157. constructed: true,
  158. value: [{
  159. name: 'pkcs-12PbeParams.salt',
  160. tagClass: asn1.Class.UNIVERSAL,
  161. type: asn1.Type.OCTETSTRING,
  162. constructed: false,
  163. capture: 'salt'
  164. }, {
  165. name: 'pkcs-12PbeParams.iterations',
  166. tagClass: asn1.Class.UNIVERSAL,
  167. type: asn1.Type.INTEGER,
  168. constructed: false,
  169. capture: 'iterations'
  170. }]
  171. };
  172. /**
  173. * Encrypts a ASN.1 PrivateKeyInfo object, producing an EncryptedPrivateKeyInfo.
  174. *
  175. * PBES2Algorithms ALGORITHM-IDENTIFIER ::=
  176. * { {PBES2-params IDENTIFIED BY id-PBES2}, ...}
  177. *
  178. * id-PBES2 OBJECT IDENTIFIER ::= {pkcs-5 13}
  179. *
  180. * PBES2-params ::= SEQUENCE {
  181. * keyDerivationFunc AlgorithmIdentifier {{PBES2-KDFs}},
  182. * encryptionScheme AlgorithmIdentifier {{PBES2-Encs}}
  183. * }
  184. *
  185. * PBES2-KDFs ALGORITHM-IDENTIFIER ::=
  186. * { {PBKDF2-params IDENTIFIED BY id-PBKDF2}, ... }
  187. *
  188. * PBES2-Encs ALGORITHM-IDENTIFIER ::= { ... }
  189. *
  190. * PBKDF2-params ::= SEQUENCE {
  191. * salt CHOICE {
  192. * specified OCTET STRING,
  193. * otherSource AlgorithmIdentifier {{PBKDF2-SaltSources}}
  194. * },
  195. * iterationCount INTEGER (1..MAX),
  196. * keyLength INTEGER (1..MAX) OPTIONAL,
  197. * prf AlgorithmIdentifier {{PBKDF2-PRFs}} DEFAULT algid-hmacWithSHA1
  198. * }
  199. *
  200. * @param obj the ASN.1 PrivateKeyInfo object.
  201. * @param password the password to encrypt with.
  202. * @param options:
  203. * algorithm the encryption algorithm to use
  204. * ('aes128', 'aes192', 'aes256', '3des'), defaults to 'aes128'.
  205. * count the iteration count to use.
  206. * saltSize the salt size to use.
  207. * prfAlgorithm the PRF message digest algorithm to use
  208. * ('sha1', 'sha224', 'sha256', 'sha384', 'sha512')
  209. *
  210. * @return the ASN.1 EncryptedPrivateKeyInfo.
  211. */
  212. pki.encryptPrivateKeyInfo = function(obj, password, options) {
  213. // set default options
  214. options = options || {};
  215. options.saltSize = options.saltSize || 8;
  216. options.count = options.count || 2048;
  217. options.algorithm = options.algorithm || 'aes128';
  218. options.prfAlgorithm = options.prfAlgorithm || 'sha1';
  219. // generate PBE params
  220. var salt = forge.random.getBytesSync(options.saltSize);
  221. var count = options.count;
  222. var countBytes = asn1.integerToDer(count);
  223. var dkLen;
  224. var encryptionAlgorithm;
  225. var encryptedData;
  226. if(options.algorithm.indexOf('aes') === 0 || options.algorithm === 'des') {
  227. // do PBES2
  228. var ivLen, encOid, cipherFn;
  229. switch(options.algorithm) {
  230. case 'aes128':
  231. dkLen = 16;
  232. ivLen = 16;
  233. encOid = oids['aes128-CBC'];
  234. cipherFn = forge.aes.createEncryptionCipher;
  235. break;
  236. case 'aes192':
  237. dkLen = 24;
  238. ivLen = 16;
  239. encOid = oids['aes192-CBC'];
  240. cipherFn = forge.aes.createEncryptionCipher;
  241. break;
  242. case 'aes256':
  243. dkLen = 32;
  244. ivLen = 16;
  245. encOid = oids['aes256-CBC'];
  246. cipherFn = forge.aes.createEncryptionCipher;
  247. break;
  248. case 'des':
  249. dkLen = 8;
  250. ivLen = 8;
  251. encOid = oids['desCBC'];
  252. cipherFn = forge.des.createEncryptionCipher;
  253. break;
  254. default:
  255. var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.');
  256. error.algorithm = options.algorithm;
  257. throw error;
  258. }
  259. // get PRF message digest
  260. var prfAlgorithm = 'hmacWith' + options.prfAlgorithm.toUpperCase();
  261. var md = prfAlgorithmToMessageDigest(prfAlgorithm);
  262. // encrypt private key using pbe SHA-1 and AES/DES
  263. var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md);
  264. var iv = forge.random.getBytesSync(ivLen);
  265. var cipher = cipherFn(dk);
  266. cipher.start(iv);
  267. cipher.update(asn1.toDer(obj));
  268. cipher.finish();
  269. encryptedData = cipher.output.getBytes();
  270. // get PBKDF2-params
  271. var params = createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm);
  272. encryptionAlgorithm = asn1.create(
  273. asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  274. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  275. asn1.oidToDer(oids['pkcs5PBES2']).getBytes()),
  276. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  277. // keyDerivationFunc
  278. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  279. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  280. asn1.oidToDer(oids['pkcs5PBKDF2']).getBytes()),
  281. // PBKDF2-params
  282. params
  283. ]),
  284. // encryptionScheme
  285. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  286. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  287. asn1.oidToDer(encOid).getBytes()),
  288. // iv
  289. asn1.create(
  290. asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, iv)
  291. ])
  292. ])
  293. ]);
  294. } else if(options.algorithm === '3des') {
  295. // Do PKCS12 PBE
  296. dkLen = 24;
  297. var saltBytes = new forge.util.ByteBuffer(salt);
  298. var dk = pki.pbe.generatePkcs12Key(password, saltBytes, 1, count, dkLen);
  299. var iv = pki.pbe.generatePkcs12Key(password, saltBytes, 2, count, dkLen);
  300. var cipher = forge.des.createEncryptionCipher(dk);
  301. cipher.start(iv);
  302. cipher.update(asn1.toDer(obj));
  303. cipher.finish();
  304. encryptedData = cipher.output.getBytes();
  305. encryptionAlgorithm = asn1.create(
  306. asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  307. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  308. asn1.oidToDer(oids['pbeWithSHAAnd3-KeyTripleDES-CBC']).getBytes()),
  309. // pkcs-12PbeParams
  310. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  311. // salt
  312. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt),
  313. // iteration count
  314. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  315. countBytes.getBytes())
  316. ])
  317. ]);
  318. } else {
  319. var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.');
  320. error.algorithm = options.algorithm;
  321. throw error;
  322. }
  323. // EncryptedPrivateKeyInfo
  324. var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  325. // encryptionAlgorithm
  326. encryptionAlgorithm,
  327. // encryptedData
  328. asn1.create(
  329. asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, encryptedData)
  330. ]);
  331. return rval;
  332. };
  333. /**
  334. * Decrypts a ASN.1 PrivateKeyInfo object.
  335. *
  336. * @param obj the ASN.1 EncryptedPrivateKeyInfo object.
  337. * @param password the password to decrypt with.
  338. *
  339. * @return the ASN.1 PrivateKeyInfo on success, null on failure.
  340. */
  341. pki.decryptPrivateKeyInfo = function(obj, password) {
  342. var rval = null;
  343. // get PBE params
  344. var capture = {};
  345. var errors = [];
  346. if(!asn1.validate(obj, encryptedPrivateKeyValidator, capture, errors)) {
  347. var error = new Error('Cannot read encrypted private key. ' +
  348. 'ASN.1 object is not a supported EncryptedPrivateKeyInfo.');
  349. error.errors = errors;
  350. throw error;
  351. }
  352. // get cipher
  353. var oid = asn1.derToOid(capture.encryptionOid);
  354. var cipher = pki.pbe.getCipher(oid, capture.encryptionParams, password);
  355. // get encrypted data
  356. var encrypted = forge.util.createBuffer(capture.encryptedData);
  357. cipher.update(encrypted);
  358. if(cipher.finish()) {
  359. rval = asn1.fromDer(cipher.output);
  360. }
  361. return rval;
  362. };
  363. /**
  364. * Converts a EncryptedPrivateKeyInfo to PEM format.
  365. *
  366. * @param epki the EncryptedPrivateKeyInfo.
  367. * @param maxline the maximum characters per line, defaults to 64.
  368. *
  369. * @return the PEM-formatted encrypted private key.
  370. */
  371. pki.encryptedPrivateKeyToPem = function(epki, maxline) {
  372. // convert to DER, then PEM-encode
  373. var msg = {
  374. type: 'ENCRYPTED PRIVATE KEY',
  375. body: asn1.toDer(epki).getBytes()
  376. };
  377. return forge.pem.encode(msg, {maxline: maxline});
  378. };
  379. /**
  380. * Converts a PEM-encoded EncryptedPrivateKeyInfo to ASN.1 format. Decryption
  381. * is not performed.
  382. *
  383. * @param pem the EncryptedPrivateKeyInfo in PEM-format.
  384. *
  385. * @return the ASN.1 EncryptedPrivateKeyInfo.
  386. */
  387. pki.encryptedPrivateKeyFromPem = function(pem) {
  388. var msg = forge.pem.decode(pem)[0];
  389. if(msg.type !== 'ENCRYPTED PRIVATE KEY') {
  390. var error = new Error('Could not convert encrypted private key from PEM; ' +
  391. 'PEM header type is "ENCRYPTED PRIVATE KEY".');
  392. error.headerType = msg.type;
  393. throw error;
  394. }
  395. if(msg.procType && msg.procType.type === 'ENCRYPTED') {
  396. throw new Error('Could not convert encrypted private key from PEM; ' +
  397. 'PEM is encrypted.');
  398. }
  399. // convert DER to ASN.1 object
  400. return asn1.fromDer(msg.body);
  401. };
  402. /**
  403. * Encrypts an RSA private key. By default, the key will be wrapped in
  404. * a PrivateKeyInfo and encrypted to produce a PKCS#8 EncryptedPrivateKeyInfo.
  405. * This is the standard, preferred way to encrypt a private key.
  406. *
  407. * To produce a non-standard PEM-encrypted private key that uses encapsulated
  408. * headers to indicate the encryption algorithm (old-style non-PKCS#8 OpenSSL
  409. * private key encryption), set the 'legacy' option to true. Note: Using this
  410. * option will cause the iteration count to be forced to 1.
  411. *
  412. * Note: The 'des' algorithm is supported, but it is not considered to be
  413. * secure because it only uses a single 56-bit key. If possible, it is highly
  414. * recommended that a different algorithm be used.
  415. *
  416. * @param rsaKey the RSA key to encrypt.
  417. * @param password the password to use.
  418. * @param options:
  419. * algorithm: the encryption algorithm to use
  420. * ('aes128', 'aes192', 'aes256', '3des', 'des').
  421. * count: the iteration count to use.
  422. * saltSize: the salt size to use.
  423. * legacy: output an old non-PKCS#8 PEM-encrypted+encapsulated
  424. * headers (DEK-Info) private key.
  425. *
  426. * @return the PEM-encoded ASN.1 EncryptedPrivateKeyInfo.
  427. */
  428. pki.encryptRsaPrivateKey = function(rsaKey, password, options) {
  429. // standard PKCS#8
  430. options = options || {};
  431. if(!options.legacy) {
  432. // encrypt PrivateKeyInfo
  433. var rval = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(rsaKey));
  434. rval = pki.encryptPrivateKeyInfo(rval, password, options);
  435. return pki.encryptedPrivateKeyToPem(rval);
  436. }
  437. // legacy non-PKCS#8
  438. var algorithm;
  439. var iv;
  440. var dkLen;
  441. var cipherFn;
  442. switch(options.algorithm) {
  443. case 'aes128':
  444. algorithm = 'AES-128-CBC';
  445. dkLen = 16;
  446. iv = forge.random.getBytesSync(16);
  447. cipherFn = forge.aes.createEncryptionCipher;
  448. break;
  449. case 'aes192':
  450. algorithm = 'AES-192-CBC';
  451. dkLen = 24;
  452. iv = forge.random.getBytesSync(16);
  453. cipherFn = forge.aes.createEncryptionCipher;
  454. break;
  455. case 'aes256':
  456. algorithm = 'AES-256-CBC';
  457. dkLen = 32;
  458. iv = forge.random.getBytesSync(16);
  459. cipherFn = forge.aes.createEncryptionCipher;
  460. break;
  461. case '3des':
  462. algorithm = 'DES-EDE3-CBC';
  463. dkLen = 24;
  464. iv = forge.random.getBytesSync(8);
  465. cipherFn = forge.des.createEncryptionCipher;
  466. break;
  467. case 'des':
  468. algorithm = 'DES-CBC';
  469. dkLen = 8;
  470. iv = forge.random.getBytesSync(8);
  471. cipherFn = forge.des.createEncryptionCipher;
  472. break;
  473. default:
  474. var error = new Error('Could not encrypt RSA private key; unsupported ' +
  475. 'encryption algorithm "' + options.algorithm + '".');
  476. error.algorithm = options.algorithm;
  477. throw error;
  478. }
  479. // encrypt private key using OpenSSL legacy key derivation
  480. var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen);
  481. var cipher = cipherFn(dk);
  482. cipher.start(iv);
  483. cipher.update(asn1.toDer(pki.privateKeyToAsn1(rsaKey)));
  484. cipher.finish();
  485. var msg = {
  486. type: 'RSA PRIVATE KEY',
  487. procType: {
  488. version: '4',
  489. type: 'ENCRYPTED'
  490. },
  491. dekInfo: {
  492. algorithm: algorithm,
  493. parameters: forge.util.bytesToHex(iv).toUpperCase()
  494. },
  495. body: cipher.output.getBytes()
  496. };
  497. return forge.pem.encode(msg);
  498. };
  499. /**
  500. * Decrypts an RSA private key.
  501. *
  502. * @param pem the PEM-formatted EncryptedPrivateKeyInfo to decrypt.
  503. * @param password the password to use.
  504. *
  505. * @return the RSA key on success, null on failure.
  506. */
  507. pki.decryptRsaPrivateKey = function(pem, password) {
  508. var rval = null;
  509. var msg = forge.pem.decode(pem)[0];
  510. if(msg.type !== 'ENCRYPTED PRIVATE KEY' &&
  511. msg.type !== 'PRIVATE KEY' &&
  512. msg.type !== 'RSA PRIVATE KEY') {
  513. var error = new Error('Could not convert private key from PEM; PEM header type ' +
  514. 'is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".');
  515. error.headerType = error;
  516. throw error;
  517. }
  518. if(msg.procType && msg.procType.type === 'ENCRYPTED') {
  519. var dkLen;
  520. var cipherFn;
  521. switch(msg.dekInfo.algorithm) {
  522. case 'DES-CBC':
  523. dkLen = 8;
  524. cipherFn = forge.des.createDecryptionCipher;
  525. break;
  526. case 'DES-EDE3-CBC':
  527. dkLen = 24;
  528. cipherFn = forge.des.createDecryptionCipher;
  529. break;
  530. case 'AES-128-CBC':
  531. dkLen = 16;
  532. cipherFn = forge.aes.createDecryptionCipher;
  533. break;
  534. case 'AES-192-CBC':
  535. dkLen = 24;
  536. cipherFn = forge.aes.createDecryptionCipher;
  537. break;
  538. case 'AES-256-CBC':
  539. dkLen = 32;
  540. cipherFn = forge.aes.createDecryptionCipher;
  541. break;
  542. case 'RC2-40-CBC':
  543. dkLen = 5;
  544. cipherFn = function(key) {
  545. return forge.rc2.createDecryptionCipher(key, 40);
  546. };
  547. break;
  548. case 'RC2-64-CBC':
  549. dkLen = 8;
  550. cipherFn = function(key) {
  551. return forge.rc2.createDecryptionCipher(key, 64);
  552. };
  553. break;
  554. case 'RC2-128-CBC':
  555. dkLen = 16;
  556. cipherFn = function(key) {
  557. return forge.rc2.createDecryptionCipher(key, 128);
  558. };
  559. break;
  560. default:
  561. var error = new Error('Could not decrypt private key; unsupported ' +
  562. 'encryption algorithm "' + msg.dekInfo.algorithm + '".');
  563. error.algorithm = msg.dekInfo.algorithm;
  564. throw error;
  565. }
  566. // use OpenSSL legacy key derivation
  567. var iv = forge.util.hexToBytes(msg.dekInfo.parameters);
  568. var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen);
  569. var cipher = cipherFn(dk);
  570. cipher.start(iv);
  571. cipher.update(forge.util.createBuffer(msg.body));
  572. if(cipher.finish()) {
  573. rval = cipher.output.getBytes();
  574. } else {
  575. return rval;
  576. }
  577. } else {
  578. rval = msg.body;
  579. }
  580. if(msg.type === 'ENCRYPTED PRIVATE KEY') {
  581. rval = pki.decryptPrivateKeyInfo(asn1.fromDer(rval), password);
  582. } else {
  583. // decryption already performed above
  584. rval = asn1.fromDer(rval);
  585. }
  586. if(rval !== null) {
  587. rval = pki.privateKeyFromAsn1(rval);
  588. }
  589. return rval;
  590. };
  591. /**
  592. * Derives a PKCS#12 key.
  593. *
  594. * @param password the password to derive the key material from, null or
  595. * undefined for none.
  596. * @param salt the salt, as a ByteBuffer, to use.
  597. * @param id the PKCS#12 ID byte (1 = key material, 2 = IV, 3 = MAC).
  598. * @param iter the iteration count.
  599. * @param n the number of bytes to derive from the password.
  600. * @param md the message digest to use, defaults to SHA-1.
  601. *
  602. * @return a ByteBuffer with the bytes derived from the password.
  603. */
  604. pki.pbe.generatePkcs12Key = function(password, salt, id, iter, n, md) {
  605. var j, l;
  606. if(typeof md === 'undefined' || md === null) {
  607. if(!('sha1' in forge.md)) {
  608. throw new Error('"sha1" hash algorithm unavailable.');
  609. }
  610. md = forge.md.sha1.create();
  611. }
  612. var u = md.digestLength;
  613. var v = md.blockLength;
  614. var result = new forge.util.ByteBuffer();
  615. /* Convert password to Unicode byte buffer + trailing 0-byte. */
  616. var passBuf = new forge.util.ByteBuffer();
  617. if(password !== null && password !== undefined) {
  618. for(l = 0; l < password.length; l++) {
  619. passBuf.putInt16(password.charCodeAt(l));
  620. }
  621. passBuf.putInt16(0);
  622. }
  623. /* Length of salt and password in BYTES. */
  624. var p = passBuf.length();
  625. var s = salt.length();
  626. /* 1. Construct a string, D (the "diversifier"), by concatenating
  627. v copies of ID. */
  628. var D = new forge.util.ByteBuffer();
  629. D.fillWithByte(id, v);
  630. /* 2. Concatenate copies of the salt together to create a string S of length
  631. v * ceil(s / v) bytes (the final copy of the salt may be trunacted
  632. to create S).
  633. Note that if the salt is the empty string, then so is S. */
  634. var Slen = v * Math.ceil(s / v);
  635. var S = new forge.util.ByteBuffer();
  636. for(l = 0; l < Slen; l++) {
  637. S.putByte(salt.at(l % s));
  638. }
  639. /* 3. Concatenate copies of the password together to create a string P of
  640. length v * ceil(p / v) bytes (the final copy of the password may be
  641. truncated to create P).
  642. Note that if the password is the empty string, then so is P. */
  643. var Plen = v * Math.ceil(p / v);
  644. var P = new forge.util.ByteBuffer();
  645. for(l = 0; l < Plen; l++) {
  646. P.putByte(passBuf.at(l % p));
  647. }
  648. /* 4. Set I=S||P to be the concatenation of S and P. */
  649. var I = S;
  650. I.putBuffer(P);
  651. /* 5. Set c=ceil(n / u). */
  652. var c = Math.ceil(n / u);
  653. /* 6. For i=1, 2, ..., c, do the following: */
  654. for(var i = 1; i <= c; i++) {
  655. /* a) Set Ai=H^r(D||I). (l.e. the rth hash of D||I, H(H(H(...H(D||I)))) */
  656. var buf = new forge.util.ByteBuffer();
  657. buf.putBytes(D.bytes());
  658. buf.putBytes(I.bytes());
  659. for(var round = 0; round < iter; round++) {
  660. md.start();
  661. md.update(buf.getBytes());
  662. buf = md.digest();
  663. }
  664. /* b) Concatenate copies of Ai to create a string B of length v bytes (the
  665. final copy of Ai may be truncated to create B). */
  666. var B = new forge.util.ByteBuffer();
  667. for(l = 0; l < v; l++) {
  668. B.putByte(buf.at(l % u));
  669. }
  670. /* c) Treating I as a concatenation I0, I1, ..., Ik-1 of v-byte blocks,
  671. where k=ceil(s / v) + ceil(p / v), modify I by setting
  672. Ij=(Ij+B+1) mod 2v for each j. */
  673. var k = Math.ceil(s / v) + Math.ceil(p / v);
  674. var Inew = new forge.util.ByteBuffer();
  675. for(j = 0; j < k; j++) {
  676. var chunk = new forge.util.ByteBuffer(I.getBytes(v));
  677. var x = 0x1ff;
  678. for(l = B.length() - 1; l >= 0; l--) {
  679. x = x >> 8;
  680. x += B.at(l) + chunk.at(l);
  681. chunk.setAt(l, x & 0xff);
  682. }
  683. Inew.putBuffer(chunk);
  684. }
  685. I = Inew;
  686. /* Add Ai to A. */
  687. result.putBuffer(buf);
  688. }
  689. result.truncate(result.length() - n);
  690. return result;
  691. };
  692. /**
  693. * Get new Forge cipher object instance.
  694. *
  695. * @param oid the OID (in string notation).
  696. * @param params the ASN.1 params object.
  697. * @param password the password to decrypt with.
  698. *
  699. * @return new cipher object instance.
  700. */
  701. pki.pbe.getCipher = function(oid, params, password) {
  702. switch(oid) {
  703. case pki.oids['pkcs5PBES2']:
  704. return pki.pbe.getCipherForPBES2(oid, params, password);
  705. case pki.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']:
  706. case pki.oids['pbewithSHAAnd40BitRC2-CBC']:
  707. return pki.pbe.getCipherForPKCS12PBE(oid, params, password);
  708. default:
  709. var error = new Error('Cannot read encrypted PBE data block. Unsupported OID.');
  710. error.oid = oid;
  711. error.supportedOids = [
  712. 'pkcs5PBES2',
  713. 'pbeWithSHAAnd3-KeyTripleDES-CBC',
  714. 'pbewithSHAAnd40BitRC2-CBC'
  715. ];
  716. throw error;
  717. }
  718. };
  719. /**
  720. * Get new Forge cipher object instance according to PBES2 params block.
  721. *
  722. * The returned cipher instance is already started using the IV
  723. * from PBES2 parameter block.
  724. *
  725. * @param oid the PKCS#5 PBKDF2 OID (in string notation).
  726. * @param params the ASN.1 PBES2-params object.
  727. * @param password the password to decrypt with.
  728. *
  729. * @return new cipher object instance.
  730. */
  731. pki.pbe.getCipherForPBES2 = function(oid, params, password) {
  732. // get PBE params
  733. var capture = {};
  734. var errors = [];
  735. if(!asn1.validate(params, PBES2AlgorithmsValidator, capture, errors)) {
  736. var error = new Error('Cannot read password-based-encryption algorithm ' +
  737. 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.');
  738. error.errors = errors;
  739. throw error;
  740. }
  741. // check oids
  742. oid = asn1.derToOid(capture.kdfOid);
  743. if(oid !== pki.oids['pkcs5PBKDF2']) {
  744. var error = new Error('Cannot read encrypted private key. ' +
  745. 'Unsupported key derivation function OID.');
  746. error.oid = oid;
  747. error.supportedOids = ['pkcs5PBKDF2'];
  748. throw error;
  749. }
  750. oid = asn1.derToOid(capture.encOid);
  751. if(oid !== pki.oids['aes128-CBC'] &&
  752. oid !== pki.oids['aes192-CBC'] &&
  753. oid !== pki.oids['aes256-CBC'] &&
  754. oid !== pki.oids['des-EDE3-CBC'] &&
  755. oid !== pki.oids['desCBC']) {
  756. var error = new Error('Cannot read encrypted private key. ' +
  757. 'Unsupported encryption scheme OID.');
  758. error.oid = oid;
  759. error.supportedOids = [
  760. 'aes128-CBC', 'aes192-CBC', 'aes256-CBC', 'des-EDE3-CBC', 'desCBC'];
  761. throw error;
  762. }
  763. // set PBE params
  764. var salt = capture.kdfSalt;
  765. var count = forge.util.createBuffer(capture.kdfIterationCount);
  766. count = count.getInt(count.length() << 3);
  767. var dkLen;
  768. var cipherFn;
  769. switch(pki.oids[oid]) {
  770. case 'aes128-CBC':
  771. dkLen = 16;
  772. cipherFn = forge.aes.createDecryptionCipher;
  773. break;
  774. case 'aes192-CBC':
  775. dkLen = 24;
  776. cipherFn = forge.aes.createDecryptionCipher;
  777. break;
  778. case 'aes256-CBC':
  779. dkLen = 32;
  780. cipherFn = forge.aes.createDecryptionCipher;
  781. break;
  782. case 'des-EDE3-CBC':
  783. dkLen = 24;
  784. cipherFn = forge.des.createDecryptionCipher;
  785. break;
  786. case 'desCBC':
  787. dkLen = 8;
  788. cipherFn = forge.des.createDecryptionCipher;
  789. break;
  790. }
  791. // get PRF message digest
  792. var md = prfOidToMessageDigest(capture.prfOid);
  793. // decrypt private key using pbe with chosen PRF and AES/DES
  794. var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md);
  795. var iv = capture.encIv;
  796. var cipher = cipherFn(dk);
  797. cipher.start(iv);
  798. return cipher;
  799. };
  800. /**
  801. * Get new Forge cipher object instance for PKCS#12 PBE.
  802. *
  803. * The returned cipher instance is already started using the key & IV
  804. * derived from the provided password and PKCS#12 PBE salt.
  805. *
  806. * @param oid The PKCS#12 PBE OID (in string notation).
  807. * @param params The ASN.1 PKCS#12 PBE-params object.
  808. * @param password The password to decrypt with.
  809. *
  810. * @return the new cipher object instance.
  811. */
  812. pki.pbe.getCipherForPKCS12PBE = function(oid, params, password) {
  813. // get PBE params
  814. var capture = {};
  815. var errors = [];
  816. if(!asn1.validate(params, pkcs12PbeParamsValidator, capture, errors)) {
  817. var error = new Error('Cannot read password-based-encryption algorithm ' +
  818. 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.');
  819. error.errors = errors;
  820. throw error;
  821. }
  822. var salt = forge.util.createBuffer(capture.salt);
  823. var count = forge.util.createBuffer(capture.iterations);
  824. count = count.getInt(count.length() << 3);
  825. var dkLen, dIvLen, cipherFn;
  826. switch(oid) {
  827. case pki.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']:
  828. dkLen = 24;
  829. dIvLen = 8;
  830. cipherFn = forge.des.startDecrypting;
  831. break;
  832. case pki.oids['pbewithSHAAnd40BitRC2-CBC']:
  833. dkLen = 5;
  834. dIvLen = 8;
  835. cipherFn = function(key, iv) {
  836. var cipher = forge.rc2.createDecryptionCipher(key, 40);
  837. cipher.start(iv, null);
  838. return cipher;
  839. };
  840. break;
  841. default:
  842. var error = new Error('Cannot read PKCS #12 PBE data block. Unsupported OID.');
  843. error.oid = oid;
  844. throw error;
  845. }
  846. // get PRF message digest
  847. var md = prfOidToMessageDigest(capture.prfOid);
  848. var key = pki.pbe.generatePkcs12Key(password, salt, 1, count, dkLen, md);
  849. md.start();
  850. var iv = pki.pbe.generatePkcs12Key(password, salt, 2, count, dIvLen, md);
  851. return cipherFn(key, iv);
  852. };
  853. /**
  854. * OpenSSL's legacy key derivation function.
  855. *
  856. * See: http://www.openssl.org/docs/crypto/EVP_BytesToKey.html
  857. *
  858. * @param password the password to derive the key from.
  859. * @param salt the salt to use, null for none.
  860. * @param dkLen the number of bytes needed for the derived key.
  861. * @param [options] the options to use:
  862. * [md] an optional message digest object to use.
  863. */
  864. pki.pbe.opensslDeriveBytes = function(password, salt, dkLen, md) {
  865. if(typeof md === 'undefined' || md === null) {
  866. if(!('md5' in forge.md)) {
  867. throw new Error('"md5" hash algorithm unavailable.');
  868. }
  869. md = forge.md.md5.create();
  870. }
  871. if(salt === null) {
  872. salt = '';
  873. }
  874. var digests = [hash(md, password + salt)];
  875. for(var length = 16, i = 1; length < dkLen; ++i, length += 16) {
  876. digests.push(hash(md, digests[i - 1] + password + salt));
  877. }
  878. return digests.join('').substr(0, dkLen);
  879. };
  880. function hash(md, bytes) {
  881. return md.start().update(bytes).digest().getBytes();
  882. }
  883. function prfOidToMessageDigest(prfOid) {
  884. // get PRF algorithm, default to SHA-1
  885. var prfAlgorithm;
  886. if(!prfOid) {
  887. prfAlgorithm = 'hmacWithSHA1';
  888. } else {
  889. prfAlgorithm = pki.oids[asn1.derToOid(prfOid)];
  890. if(!prfAlgorithm) {
  891. var error = new Error('Unsupported PRF OID.');
  892. error.oid = prfOid;
  893. error.supported = [
  894. 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384',
  895. 'hmacWithSHA512'];
  896. throw error;
  897. }
  898. }
  899. return prfAlgorithmToMessageDigest(prfAlgorithm);
  900. }
  901. function prfAlgorithmToMessageDigest(prfAlgorithm) {
  902. var factory = forge.md;
  903. switch(prfAlgorithm) {
  904. case 'hmacWithSHA224':
  905. factory = forge.md.sha512;
  906. case 'hmacWithSHA1':
  907. case 'hmacWithSHA256':
  908. case 'hmacWithSHA384':
  909. case 'hmacWithSHA512':
  910. prfAlgorithm = prfAlgorithm.substr(8).toLowerCase();
  911. break;
  912. default:
  913. var error = new Error('Unsupported PRF algorithm.');
  914. error.algorithm = prfAlgorithm;
  915. error.supported = [
  916. 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384',
  917. 'hmacWithSHA512'];
  918. throw error;
  919. }
  920. if(!factory || !(prfAlgorithm in factory)) {
  921. throw new Error('Unknown hash algorithm: ' + prfAlgorithm);
  922. }
  923. return factory[prfAlgorithm].create();
  924. }
  925. function createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm) {
  926. var params = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  927. // salt
  928. asn1.create(
  929. asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt),
  930. // iteration count
  931. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  932. countBytes.getBytes())
  933. ]);
  934. // when PRF algorithm is not SHA-1 default, add key length and PRF algorithm
  935. if(prfAlgorithm !== 'hmacWithSHA1') {
  936. params.value.push(
  937. // key length
  938. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  939. forge.util.hexToBytes(dkLen.toString(16))),
  940. // AlgorithmIdentifier
  941. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  942. // algorithm
  943. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  944. asn1.oidToDer(pki.oids[prfAlgorithm]).getBytes()),
  945. // parameters (null)
  946. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')
  947. ]));
  948. }
  949. return params;
  950. }