1 // Copyright 2015 Joyent, Inc.
8 var assert = require('assert-plus');
9 var rfc4253 = require('./rfc4253');
10 var utils = require('../utils');
11 var Key = require('../key');
12 var PrivateKey = require('../private-key');
14 var sshpriv = require('./ssh-private');
17 var SSHKEY_RE = /^([a-z0-9-]+)[ \t]+([a-zA-Z0-9+\/]+[=]*)([\n \t]+([^\n]+))?$/;
19 var SSHKEY_RE2 = /^([a-z0-9-]+)[ \t]+([a-zA-Z0-9+\/ \t\n]+[=]*)(.*)$/;
21 function read(buf, options) {
22 if (typeof (buf) !== 'string') {
23 assert.buffer(buf, 'buf');
24 buf = buf.toString('ascii');
27 var trimmed = buf.trim().replace(/[\\\r]/g, '');
28 var m = trimmed.match(SSHKEY_RE);
30 m = trimmed.match(SSHKEY_RE2);
31 assert.ok(m, 'key must match regex');
33 var type = rfc4253.algToKeyType(m[1]);
34 var kbuf = new Buffer(m[2], 'base64');
37 * This is a bit tricky. If we managed to parse the key and locate the
38 * key comment with the regex, then do a non-partial read and assert
39 * that we have consumed all bytes. If we couldn't locate the key
40 * comment, though, there may be whitespace shenanigans going on that
41 * have conjoined the comment to the rest of the key. We do a partial
42 * read in this case to try to make the best out of a sorry situation.
48 key = rfc4253.read(kbuf);
51 m = trimmed.match(SSHKEY_RE2);
52 assert.ok(m, 'key must match regex');
53 kbuf = new Buffer(m[2], 'base64');
54 key = rfc4253.readInternal(ret, 'public', kbuf);
57 key = rfc4253.readInternal(ret, 'public', kbuf);
60 assert.strictEqual(type, key.type);
62 if (m[4] && m[4].length > 0) {
65 } else if (ret.consumed) {
67 * Now the magic: trying to recover the key comment when it's
68 * gotten conjoined to the key or otherwise shenanigan'd.
70 * Work out how much base64 we used, then drop all non-base64
71 * chars from the beginning up to this point in the the string.
72 * Then offset in this and try to make up for missing = chars.
74 var data = m[2] + m[3];
75 var realOffset = Math.ceil(ret.consumed / 3) * 4;
76 data = data.slice(0, realOffset - 2). /*JSSTYLED*/
77 replace(/[^a-zA-Z0-9+\/=]/g, '') +
78 data.slice(realOffset - 2);
80 var padding = ret.consumed % 3;
82 data.slice(realOffset - 1, realOffset) !== '=')
84 while (data.slice(realOffset, realOffset + 1) === '=')
87 /* Finally, grab what we think is the comment & clean it up. */
88 var trailer = data.slice(realOffset);
89 trailer = trailer.replace(/[\r\n]/g, ' ').
91 if (trailer.match(/^[a-zA-Z0-9]/))
92 key.comment = trailer;
98 function write(key, options) {
101 throw (new Error('Must be a public key'));
104 var alg = rfc4253.keyTypeToAlg(key);
107 var buf = rfc4253.write(key);
108 parts.push(buf.toString('base64'));
111 parts.push(key.comment);
113 return (new Buffer(parts.join(' ')));