pem.js 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. // Copyright 2015 Joyent, Inc.
  2. module.exports = {
  3. read: read,
  4. write: write
  5. };
  6. var assert = require('assert-plus');
  7. var asn1 = require('asn1');
  8. var crypto = require('crypto');
  9. var algs = require('../algs');
  10. var utils = require('../utils');
  11. var Key = require('../key');
  12. var PrivateKey = require('../private-key');
  13. var pkcs1 = require('./pkcs1');
  14. var pkcs8 = require('./pkcs8');
  15. var sshpriv = require('./ssh-private');
  16. var rfc4253 = require('./rfc4253');
  17. var errors = require('../errors');
  18. /*
  19. * For reading we support both PKCS#1 and PKCS#8. If we find a private key,
  20. * we just take the public component of it and use that.
  21. */
  22. function read(buf, options, forceType) {
  23. var input = buf;
  24. if (typeof (buf) !== 'string') {
  25. assert.buffer(buf, 'buf');
  26. buf = buf.toString('ascii');
  27. }
  28. var lines = buf.trim().split('\n');
  29. var m = lines[0].match(/*JSSTYLED*/
  30. /[-]+[ ]*BEGIN ([A-Z0-9]+ )?(PUBLIC|PRIVATE) KEY[ ]*[-]+/);
  31. assert.ok(m, 'invalid PEM header');
  32. var m2 = lines[lines.length - 1].match(/*JSSTYLED*/
  33. /[-]+[ ]*END ([A-Z0-9]+ )?(PUBLIC|PRIVATE) KEY[ ]*[-]+/);
  34. assert.ok(m2, 'invalid PEM footer');
  35. /* Begin and end banners must match key type */
  36. assert.equal(m[2], m2[2]);
  37. var type = m[2].toLowerCase();
  38. var alg;
  39. if (m[1]) {
  40. /* They also must match algorithms, if given */
  41. assert.equal(m[1], m2[1], 'PEM header and footer mismatch');
  42. alg = m[1].trim();
  43. }
  44. var headers = {};
  45. while (true) {
  46. lines = lines.slice(1);
  47. m = lines[0].match(/*JSSTYLED*/
  48. /^([A-Za-z0-9-]+): (.+)$/);
  49. if (!m)
  50. break;
  51. headers[m[1].toLowerCase()] = m[2];
  52. }
  53. var cipher, key, iv;
  54. if (headers['proc-type']) {
  55. var parts = headers['proc-type'].split(',');
  56. if (parts[0] === '4' && parts[1] === 'ENCRYPTED') {
  57. if (typeof (options.passphrase) === 'string') {
  58. options.passphrase = new Buffer(
  59. options.passphrase, 'utf-8');
  60. }
  61. if (!Buffer.isBuffer(options.passphrase)) {
  62. throw (new errors.KeyEncryptedError(
  63. options.filename, 'PEM'));
  64. } else {
  65. parts = headers['dek-info'].split(',');
  66. assert.ok(parts.length === 2);
  67. cipher = parts[0].toLowerCase();
  68. iv = new Buffer(parts[1], 'hex');
  69. key = utils.opensslKeyDeriv(cipher, iv,
  70. options.passphrase, 1).key;
  71. }
  72. }
  73. }
  74. /* Chop off the first and last lines */
  75. lines = lines.slice(0, -1).join('');
  76. buf = new Buffer(lines, 'base64');
  77. if (cipher && key && iv) {
  78. var cipherStream = crypto.createDecipheriv(cipher, key, iv);
  79. var chunk, chunks = [];
  80. cipherStream.once('error', function (e) {
  81. if (e.toString().indexOf('bad decrypt') !== -1) {
  82. throw (new Error('Incorrect passphrase ' +
  83. 'supplied, could not decrypt key'));
  84. }
  85. throw (e);
  86. });
  87. cipherStream.write(buf);
  88. cipherStream.end();
  89. while ((chunk = cipherStream.read()) !== null)
  90. chunks.push(chunk);
  91. buf = Buffer.concat(chunks);
  92. }
  93. /* The new OpenSSH internal format abuses PEM headers */
  94. if (alg && alg.toLowerCase() === 'openssh')
  95. return (sshpriv.readSSHPrivate(type, buf, options));
  96. if (alg && alg.toLowerCase() === 'ssh2')
  97. return (rfc4253.readType(type, buf, options));
  98. var der = new asn1.BerReader(buf);
  99. der.originalInput = input;
  100. /*
  101. * All of the PEM file types start with a sequence tag, so chop it
  102. * off here
  103. */
  104. der.readSequence();
  105. /* PKCS#1 type keys name an algorithm in the banner explicitly */
  106. if (alg) {
  107. if (forceType)
  108. assert.strictEqual(forceType, 'pkcs1');
  109. return (pkcs1.readPkcs1(alg, type, der));
  110. } else {
  111. if (forceType)
  112. assert.strictEqual(forceType, 'pkcs8');
  113. return (pkcs8.readPkcs8(alg, type, der));
  114. }
  115. }
  116. function write(key, options, type) {
  117. assert.object(key);
  118. var alg = {'ecdsa': 'EC', 'rsa': 'RSA', 'dsa': 'DSA'}[key.type];
  119. var header;
  120. var der = new asn1.BerWriter();
  121. if (PrivateKey.isPrivateKey(key)) {
  122. if (type && type === 'pkcs8') {
  123. header = 'PRIVATE KEY';
  124. pkcs8.writePkcs8(der, key);
  125. } else {
  126. if (type)
  127. assert.strictEqual(type, 'pkcs1');
  128. header = alg + ' PRIVATE KEY';
  129. pkcs1.writePkcs1(der, key);
  130. }
  131. } else if (Key.isKey(key)) {
  132. if (type && type === 'pkcs1') {
  133. header = alg + ' PUBLIC KEY';
  134. pkcs1.writePkcs1(der, key);
  135. } else {
  136. if (type)
  137. assert.strictEqual(type, 'pkcs8');
  138. header = 'PUBLIC KEY';
  139. pkcs8.writePkcs8(der, key);
  140. }
  141. } else {
  142. throw (new Error('key is not a Key or PrivateKey'));
  143. }
  144. var tmp = der.buffer.toString('base64');
  145. var len = tmp.length + (tmp.length / 64) +
  146. 18 + 16 + header.length*2 + 10;
  147. var buf = new Buffer(len);
  148. var o = 0;
  149. o += buf.write('-----BEGIN ' + header + '-----\n', o);
  150. for (var i = 0; i < tmp.length; ) {
  151. var limit = i + 64;
  152. if (limit > tmp.length)
  153. limit = tmp.length;
  154. o += buf.write(tmp.slice(i, limit), o);
  155. buf[o++] = 10;
  156. i = limit;
  157. }
  158. o += buf.write('-----END ' + header + '-----\n', o);
  159. return (buf.slice(0, o));
  160. }