pem.js 4.8 KB

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