1 // Copyright 2012 Joyent, Inc. All rights reserved.
3 var assert = require('assert-plus');
4 var sshpk = require('sshpk');
5 var util = require('util');
19 function HttpSignatureError(message, caller) {
20 if (Error.captureStackTrace)
21 Error.captureStackTrace(this, caller || HttpSignatureError);
23 this.message = message;
24 this.name = caller.name;
26 util.inherits(HttpSignatureError, Error);
28 function InvalidAlgorithmError(message) {
29 HttpSignatureError.call(this, message, InvalidAlgorithmError);
31 util.inherits(InvalidAlgorithmError, HttpSignatureError);
33 function validateAlgorithm(algorithm) {
34 var alg = algorithm.toLowerCase().split('-');
36 if (alg.length !== 2) {
37 throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' is not a ' +
41 if (alg[0] !== 'hmac' && !PK_ALGOS[alg[0]]) {
42 throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' type keys ' +
43 'are not supported'));
46 if (!HASH_ALGOS[alg[1]]) {
47 throw (new InvalidAlgorithmError(alg[1].toUpperCase() + ' is not a ' +
48 'supported hash algorithm'));
58 HASH_ALGOS: HASH_ALGOS,
61 HttpSignatureError: HttpSignatureError,
62 InvalidAlgorithmError: InvalidAlgorithmError,
64 validateAlgorithm: validateAlgorithm,
67 * Converts an OpenSSH public key (rsa only) to a PKCS#8 PEM file.
69 * The intent of this module is to interoperate with OpenSSL only,
70 * specifically the node crypto module's `verify` method.
72 * @param {String} key an OpenSSH public key.
73 * @return {String} PEM encoded form of the RSA public key.
74 * @throws {TypeError} on bad input.
75 * @throws {Error} on invalid ssh key formatted data.
77 sshKeyToPEM: function sshKeyToPEM(key) {
78 assert.string(key, 'ssh_key');
80 var k = sshpk.parseKey(key, 'ssh');
81 return (k.toString('pem'));
86 * Generates an OpenSSH fingerprint from an ssh public key.
88 * @param {String} key an OpenSSH public key.
89 * @return {String} key fingerprint.
90 * @throws {TypeError} on bad input.
91 * @throws {Error} if what you passed doesn't look like an ssh public key.
93 fingerprint: function fingerprint(key) {
94 assert.string(key, 'ssh_key');
96 var k = sshpk.parseKey(key, 'ssh');
97 return (k.fingerprint('md5').toString('hex'));
101 * Converts a PKGCS#8 PEM file to an OpenSSH public key (rsa)
103 * The reverse of the above function.
105 pemToRsaSSHKey: function pemToRsaSSHKey(pem, comment) {
106 assert.equal('string', typeof (pem), 'typeof pem');
108 var k = sshpk.parseKey(pem, 'pem');
110 return (k.toString('ssh'));