Initial commit
[yaffs-website] / node_modules / sshpk / lib / formats / auto.js
1 // Copyright 2015 Joyent, Inc.
2
3 module.exports = {
4         read: read,
5         write: write
6 };
7
8 var assert = require('assert-plus');
9 var utils = require('../utils');
10 var Key = require('../key');
11 var PrivateKey = require('../private-key');
12
13 var pem = require('./pem');
14 var ssh = require('./ssh');
15 var rfc4253 = require('./rfc4253');
16
17 function read(buf, options) {
18         if (typeof (buf) === 'string') {
19                 if (buf.trim().match(/^[-]+[ ]*BEGIN/))
20                         return (pem.read(buf, options));
21                 if (buf.match(/^\s*ssh-[a-z]/))
22                         return (ssh.read(buf, options));
23                 if (buf.match(/^\s*ecdsa-/))
24                         return (ssh.read(buf, options));
25                 buf = new Buffer(buf, 'binary');
26         } else {
27                 assert.buffer(buf);
28                 if (findPEMHeader(buf))
29                         return (pem.read(buf, options));
30                 if (findSSHHeader(buf))
31                         return (ssh.read(buf, options));
32         }
33         if (buf.readUInt32BE(0) < buf.length)
34                 return (rfc4253.read(buf, options));
35         throw (new Error('Failed to auto-detect format of key'));
36 }
37
38 function findSSHHeader(buf) {
39         var offset = 0;
40         while (offset < buf.length &&
41             (buf[offset] === 32 || buf[offset] === 10 || buf[offset] === 9))
42                 ++offset;
43         if (offset + 4 <= buf.length &&
44             buf.slice(offset, offset + 4).toString('ascii') === 'ssh-')
45                 return (true);
46         if (offset + 6 <= buf.length &&
47             buf.slice(offset, offset + 6).toString('ascii') === 'ecdsa-')
48                 return (true);
49         return (false);
50 }
51
52 function findPEMHeader(buf) {
53         var offset = 0;
54         while (offset < buf.length &&
55             (buf[offset] === 32 || buf[offset] === 10))
56                 ++offset;
57         if (buf[offset] !== 45)
58                 return (false);
59         while (offset < buf.length &&
60             (buf[offset] === 45))
61                 ++offset;
62         while (offset < buf.length &&
63             (buf[offset] === 32))
64                 ++offset;
65         if (offset + 5 > buf.length ||
66             buf.slice(offset, offset + 5).toString('ascii') !== 'BEGIN')
67                 return (false);
68         return (true);
69 }
70
71 function write(key, options) {
72         throw (new Error('"auto" format cannot be used for writing'));
73 }