4 Parse, convert, fingerprint and use SSH keys (both public and private) in pure
5 node -- no `ssh-keygen` or other external dependencies.
7 Supports RSA, DSA, ECDSA (nistp-\*) and ED25519 key types, in PEM (PKCS#1,
8 PKCS#8) and OpenSSH formats.
10 This library has been extracted from
11 [`node-http-signature`](https://github.com/joyent/node-http-signature)
12 (work by [Mark Cavage](https://github.com/mcavage) and
13 [Dave Eddy](https://github.com/bahamas10)) and
14 [`node-ssh-fingerprint`](https://github.com/bahamas10/node-ssh-fingerprint)
15 (work by Dave Eddy), with additions (including ECDSA support) by
16 [Alex Wilson](https://github.com/arekinath).
29 var sshpk = require('sshpk');
31 var fs = require('fs');
33 /* Read in an OpenSSH-format public key */
34 var keyPub = fs.readFileSync('id_rsa.pub');
35 var key = sshpk.parseKey(keyPub, 'ssh');
37 /* Get metadata about the key */
38 console.log('type => %s', key.type);
39 console.log('size => %d bits', key.size);
40 console.log('comment => %s', key.comment);
42 /* Compute key fingerprints, in new OpenSSH (>6.7) format, and old MD5 */
43 console.log('fingerprint => %s', key.fingerprint().toString());
44 console.log('old-style fingerprint => %s', key.fingerprint('md5').toString());
52 comment => foo@foo.com
53 fingerprint => SHA256:PYC9kPVC6J873CSIbfp0LwYeczP/W4ffObNCuDJ1u5w
54 old-style fingerprint => a0:c8:ad:6c:32:9a:32:fa:59:cc:a9:8c:0a:0d:6e:bd
57 More examples: converting between formats:
60 /* Read in a PEM public key */
61 var keyPem = fs.readFileSync('id_rsa.pem');
62 var key = sshpk.parseKey(keyPem, 'pem');
64 /* Convert to PEM PKCS#8 public key format */
65 var pemBuf = key.toBuffer('pkcs8');
67 /* Convert to SSH public key format (and return as a string) */
68 var sshKey = key.toString('ssh');
71 Signing and verifying:
74 /* Read in an OpenSSH/PEM *private* key */
75 var keyPriv = fs.readFileSync('id_ecdsa');
76 var key = sshpk.parsePrivateKey(keyPriv, 'pem');
78 var data = 'some data';
80 /* Sign some data with the key */
81 var s = key.createSign('sha1');
83 var signature = s.sign();
85 /* Now load the public key (could also use just key.toPublic()) */
86 var keyPub = fs.readFileSync('id_ecdsa.pub');
87 key = sshpk.parseKey(keyPub, 'ssh');
89 /* Make a crypto.Verifier with this key */
90 var v = key.createVerify('sha1');
92 var valid = v.verify(signature);
96 Matching fingerprints with keys:
99 var fp = sshpk.parseFingerprint('SHA256:PYC9kPVC6J873CSIbfp0LwYeczP/W4ffObNCuDJ1u5w');
101 var keys = [sshpk.parseKey(...), sshpk.parseKey(...), ...];
103 keys.forEach(function (key) {
105 console.log('found it!');
114 ### `parseKey(data[, format = 'auto'[, options]])`
116 Parses a key from a given data format and returns a new `Key` object.
120 - `data` -- Either a Buffer or String, containing the key
121 - `format` -- String name of format to use, valid options are:
122 - `auto`: choose automatically from all below
123 - `pem`: supports both PKCS#1 and PKCS#8
124 - `ssh`: standard OpenSSH format,
125 - `pkcs1`, `pkcs8`: variants of `pem`
126 - `rfc4253`: raw OpenSSH wire format
127 - `openssh`: new post-OpenSSH 6.5 internal format, produced by
129 - `options` -- Optional Object, extra options, with keys:
130 - `filename` -- Optional String, name for the key being parsed
131 (eg. the filename that was opened). Used to generate
133 - `passphrase` -- Optional String, encryption passphrase used to decrypt an
138 Returns `true` if the given object is a valid `Key` object created by a version
139 of `sshpk` compatible with this one.
143 - `obj` -- Object to identify
147 String, the type of key. Valid options are `rsa`, `dsa`, `ecdsa`.
151 Integer, "size" of the key in bits. For RSA/DSA this is the size of the modulus;
152 for ECDSA this is the bit size of the curve in use.
156 Optional string, a key comment used by some formats (eg the `ssh` format).
160 Only present if `this.type === 'ecdsa'`, string containing the name of the
161 named curve used with this key. Possible values include `nistp256`, `nistp384`
164 ### `Key#toBuffer([format = 'ssh'])`
166 Convert the key into a given data format and return the serialized key as
171 - `format` -- String name of format to use, for valid options see `parseKey()`
173 ### `Key#toString([format = 'ssh])`
175 Same as `this.toBuffer(format).toString()`.
177 ### `Key#fingerprint([algorithm = 'sha256'])`
179 Creates a new `Fingerprint` object representing this Key's fingerprint.
183 - `algorithm` -- String name of hash algorithm to use, valid options are `md5`,
184 `sha1`, `sha256`, `sha384`, `sha512`
186 ### `Key#createVerify([hashAlgorithm])`
188 Creates a `crypto.Verifier` specialized to use this Key (and the correct public
189 key algorithm to match it). The returned Verifier has the same API as a regular
190 one, except that the `verify()` function takes only the target signature as an
195 - `hashAlgorithm` -- optional String name of hash algorithm to use, any
196 supported by OpenSSL are valid, usually including
199 `v.verify(signature[, format])` Parameters
201 - `signature` -- either a Signature object, or a Buffer or String
202 - `format` -- optional String, name of format to interpret given String with.
203 Not valid if `signature` is a Signature or Buffer.
205 ### `Key#createDiffieHellman()`
208 Creates a Diffie-Hellman key exchange object initialized with this key and all
209 necessary parameters. This has the same API as a `crypto.DiffieHellman`
210 instance, except that functions take `Key` and `PrivateKey` objects as
211 arguments, and return them where indicated for.
213 This is only valid for keys belonging to a cryptosystem that supports DHE
214 or a close analogue (i.e. `dsa`, `ecdsa` and `curve25519` keys). An attempt
215 to call this function on other keys will yield an `Error`.
219 ### `parsePrivateKey(data[, format = 'auto'[, options]])`
221 Parses a private key from a given data format and returns a new
226 - `data` -- Either a Buffer or String, containing the key
227 - `format` -- String name of format to use, valid options are:
228 - `auto`: choose automatically from all below
229 - `pem`: supports both PKCS#1 and PKCS#8
230 - `ssh`, `openssh`: new post-OpenSSH 6.5 internal format, produced by
232 - `pkcs1`, `pkcs8`: variants of `pem`
233 - `rfc4253`: raw OpenSSH wire format
234 - `options` -- Optional Object, extra options, with keys:
235 - `filename` -- Optional String, name for the key being parsed
236 (eg. the filename that was opened). Used to generate
238 - `passphrase` -- Optional String, encryption passphrase used to decrypt an
241 ### `PrivateKey.isPrivateKey(obj)`
243 Returns `true` if the given object is a valid `PrivateKey` object created by a
244 version of `sshpk` compatible with this one.
248 - `obj` -- Object to identify
250 ### `PrivateKey#type`
252 String, the type of key. Valid options are `rsa`, `dsa`, `ecdsa`.
254 ### `PrivateKey#size`
256 Integer, "size" of the key in bits. For RSA/DSA this is the size of the modulus;
257 for ECDSA this is the bit size of the curve in use.
259 ### `PrivateKey#curve`
261 Only present if `this.type === 'ecdsa'`, string containing the name of the
262 named curve used with this key. Possible values include `nistp256`, `nistp384`
265 ### `PrivateKey#toBuffer([format = 'pkcs1'])`
267 Convert the key into a given data format and return the serialized key as
272 - `format` -- String name of format to use, valid options are listed under
273 `parsePrivateKey`. Note that ED25519 keys default to `openssh`
274 format instead (as they have no `pkcs1` representation).
276 ### `PrivateKey#toString([format = 'pkcs1'])`
278 Same as `this.toBuffer(format).toString()`.
280 ### `PrivateKey#toPublic()`
282 Extract just the public part of this private key, and return it as a `Key`
285 ### `PrivateKey#fingerprint([algorithm = 'sha256'])`
287 Same as `this.toPublic().fingerprint()`.
289 ### `PrivateKey#createVerify([hashAlgorithm])`
291 Same as `this.toPublic().createVerify()`.
293 ### `PrivateKey#createSign([hashAlgorithm])`
295 Creates a `crypto.Sign` specialized to use this PrivateKey (and the correct
296 key algorithm to match it). The returned Signer has the same API as a regular
297 one, except that the `sign()` function takes no arguments, and returns a
302 - `hashAlgorithm` -- optional String name of hash algorithm to use, any
303 supported by OpenSSL are valid, usually including
306 `v.sign()` Parameters
310 ### `PrivateKey#derive(newType)`
312 Derives a related key of type `newType` from this key. Currently this is
313 only supported to change between `ed25519` and `curve25519` keys which are
314 stored with the same private key (but usually distinct public keys in order
315 to avoid degenerate keys that lead to a weak Diffie-Hellman exchange).
319 - `newType` -- String, type of key to derive, either `ed25519` or `curve25519`
323 ### `parseFingerprint(fingerprint[, algorithms])`
325 Pre-parses a fingerprint, creating a `Fingerprint` object that can be used to
326 quickly locate a key by using the `Fingerprint#matches` function.
330 - `fingerprint` -- String, the fingerprint value, in any supported format
331 - `algorithms` -- Optional list of strings, names of hash algorithms to limit
332 support to. If `fingerprint` uses a hash algorithm not on
333 this list, throws `InvalidAlgorithmError`.
335 ### `Fingerprint.isFingerprint(obj)`
337 Returns `true` if the given object is a valid `Fingerprint` object created by a
338 version of `sshpk` compatible with this one.
342 - `obj` -- Object to identify
344 ### `Fingerprint#toString([format])`
346 Returns a fingerprint as a string, in the given format.
350 - `format` -- Optional String, format to use, valid options are `hex` and
351 `base64`. If this `Fingerprint` uses the `md5` algorithm, the
352 default format is `hex`. Otherwise, the default is `base64`.
354 ### `Fingerprint#matches(key)`
356 Verifies whether or not this `Fingerprint` matches a given `Key`. This function
357 uses double-hashing to avoid leaking timing information. Returns a boolean.
361 - `key` -- a `Key` object, the key to match this fingerprint against
365 ### `parseSignature(signature, algorithm, format)`
367 Parses a signature in a given format, creating a `Signature` object. Useful
368 for converting between the SSH and ASN.1 (PKCS/OpenSSL) signature formats, and
369 also returned as output from `PrivateKey#createSign().sign()`.
371 A Signature object can also be passed to a verifier produced by
372 `Key#createVerify()` and it will automatically be converted internally into the
373 correct format for verification.
377 - `signature` -- a Buffer (binary) or String (base64), data of the actual
378 signature in the given format
379 - `algorithm` -- a String, name of the algorithm to be used, possible values
380 are `rsa`, `dsa`, `ecdsa`
381 - `format` -- a String, either `asn1` or `ssh`
383 ### `Signature.isSignature(obj)`
385 Returns `true` if the given object is a valid `Signature` object created by a
386 version of `sshpk` compatible with this one.
390 - `obj` -- Object to identify
392 ### `Signature#toBuffer([format = 'asn1'])`
394 Converts a Signature to the given format and returns it as a Buffer.
398 - `format` -- a String, either `asn1` or `ssh`
400 ### `Signature#toString([format = 'asn1'])`
402 Same as `this.toBuffer(format).toString('base64')`.
406 `sshpk` includes basic support for parsing certificates in X.509 (PEM) format
407 and the OpenSSH certificate format. This feature is intended to be used mainly
408 to access basic metadata about certificates, extract public keys from them, and
409 also to generate simple self-signed certificates from an existing key.
411 Notably, there is no implementation of CA chain-of-trust verification, and only
412 very minimal support for key usage restrictions. Please do the security world
413 a favour, and DO NOT use this code for certificate verification in the
414 traditional X.509 CA chain style.
416 ### `parseCertificate(data, format)`
420 - `data` -- a Buffer or String
421 - `format` -- a String, format to use, one of `'openssh'`, `'pem'` (X.509 in a
422 PEM wrapper), or `'x509'` (raw DER encoded)
424 ### `createSelfSignedCertificate(subject, privateKey[, options])`
428 - `subject` -- an Identity, the subject of the certificate
429 - `privateKey` -- a PrivateKey, the key of the subject: will be used both to be
430 placed in the certificate and also to sign it (since this is
431 a self-signed certificate)
432 - `options` -- optional Object, with keys:
433 - `lifetime` -- optional Number, lifetime of the certificate from now in
435 - `validFrom`, `validUntil` -- optional Dates, beginning and end of
436 certificate validity period. If given
437 `lifetime` will be ignored
438 - `serial` -- optional Buffer, the serial number of the certificate
439 - `purposes` -- optional Array of String, X.509 key usage restrictions
441 ### `createCertificate(subject, key, issuer, issuerKey[, options])`
445 - `subject` -- an Identity, the subject of the certificate
446 - `key` -- a Key, the public key of the subject
447 - `issuer` -- an Identity, the issuer of the certificate who will sign it
448 - `issuerKey` -- a PrivateKey, the issuer's private key for signing
449 - `options` -- optional Object, with keys:
450 - `lifetime` -- optional Number, lifetime of the certificate from now in
452 - `validFrom`, `validUntil` -- optional Dates, beginning and end of
453 certificate validity period. If given
454 `lifetime` will be ignored
455 - `serial` -- optional Buffer, the serial number of the certificate
456 - `purposes` -- optional Array of String, X.509 key usage restrictions
458 ### `Certificate#subjects`
460 Array of `Identity` instances describing the subject of this certificate.
462 ### `Certificate#issuer`
464 The `Identity` of the Certificate's issuer (signer).
466 ### `Certificate#subjectKey`
468 The public key of the subject of the certificate, as a `Key` instance.
470 ### `Certificate#issuerKey`
472 The public key of the signing issuer of this certificate, as a `Key` instance.
473 May be `undefined` if the issuer's key is unknown (e.g. on an X509 certificate).
475 ### `Certificate#serial`
477 The serial number of the certificate. As this is normally a 64-bit or wider
478 integer, it is returned as a Buffer.
480 ### `Certificate#purposes`
482 Array of Strings indicating the X.509 key usage purposes that this certificate
483 is valid for. The possible strings at the moment are:
485 * `'signature'` -- key can be used for digital signatures
486 * `'identity'` -- key can be used to attest about the identity of the signer
487 (X.509 calls this `nonRepudiation`)
488 * `'codeSigning'` -- key can be used to sign executable code
489 * `'keyEncryption'` -- key can be used to encrypt other keys
490 * `'encryption'` -- key can be used to encrypt data (only applies for RSA)
491 * `'keyAgreement'` -- key can be used for key exchange protocols such as
493 * `'ca'` -- key can be used to sign other certificates (is a Certificate
495 * `'crl'` -- key can be used to sign Certificate Revocation Lists (CRLs)
497 ### `Certificate#isExpired([when])`
499 Tests whether the Certificate is currently expired (i.e. the `validFrom` and
500 `validUntil` dates specify a range of time that does not include the current
505 - `when` -- optional Date, if specified, tests whether the Certificate was or
506 will be expired at the specified time instead of now
510 ### `Certificate#isSignedByKey(key)`
512 Tests whether the Certificate was validly signed by the given (public) Key.
516 - `key` -- a Key instance
520 ### `Certificate#isSignedBy(certificate)`
522 Tests whether this Certificate was validly signed by the subject of the given
523 certificate. Also tests that the issuer Identity of this Certificate and the
524 subject Identity of the other Certificate are equivalent.
528 - `certificate` -- another Certificate instance
532 ### `Certificate#fingerprint([hashAlgo])`
534 Returns the X509-style fingerprint of the entire certificate (as a Fingerprint
535 instance). This matches what a web-browser or similar would display as the
536 certificate fingerprint and should not be confused with the fingerprint of the
537 subject's public key.
541 - `hashAlgo` -- an optional String, any hash function name
543 ### `Certificate#toBuffer([format])`
545 Serializes the Certificate to a Buffer and returns it.
549 - `format` -- an optional String, output format, one of `'openssh'`, `'pem'` or
550 `'x509'`. Defaults to `'x509'`.
554 ### `Certificate#toString([format])`
556 - `format` -- an optional String, output format, one of `'openssh'`, `'pem'` or
557 `'x509'`. Defaults to `'pem'`.
561 ## Certificate identities
563 ### `identityForHost(hostname)`
565 Constructs a host-type Identity for a given hostname.
569 - `hostname` -- the fully qualified DNS name of the host
571 Returns an Identity instance.
573 ### `identityForUser(uid)`
575 Constructs a user-type Identity for a given UID.
579 - `uid` -- a String, user identifier (login name)
581 Returns an Identity instance.
583 ### `identityForEmail(email)`
585 Constructs an email-type Identity for a given email address.
589 - `email` -- a String, email address
591 Returns an Identity instance.
593 ### `identityFromDN(dn)`
595 Parses an LDAP-style DN string (e.g. `'CN=foo, C=US'`) and turns it into an
602 Returns an Identity instance.
604 ### `Identity#toString()`
606 Returns the identity as an LDAP-style DN string.
607 e.g. `'CN=foo, O=bar corp, C=us'`
611 The type of identity. One of `'host'`, `'user'`, `'email'` or `'unknown'`
613 ### `Identity#hostname`
617 Set when `type` is `'host'`, `'user'`, or `'email'`, respectively. Strings.
621 The value of the first `CN=` in the DN, if any.
626 ### `InvalidAlgorithmError`
628 The specified algorithm is not valid, either because it is not supported, or
629 because it was not included on a list of allowed algorithms.
631 Thrown by `Fingerprint.parse`, `Key#fingerprint`.
635 - `algorithm` -- the algorithm that could not be validated
637 ### `FingerprintFormatError`
639 The fingerprint string given could not be parsed as a supported fingerprint
640 format, or the specified fingerprint format is invalid.
642 Thrown by `Fingerprint.parse`, `Fingerprint#toString`.
646 - `fingerprint` -- if caused by a fingerprint, the string value given
647 - `format` -- if caused by an invalid format specification, the string value given
651 The key data given could not be parsed as a valid key.
655 - `keyName` -- `filename` that was given to `parseKey`
656 - `format` -- the `format` that was trying to parse the key (see `parseKey`)
657 - `innerErr` -- the inner Error thrown by the format parser
659 ### `KeyEncryptedError`
661 The key is encrypted with a symmetric key (ie, it is password protected). The
662 parsing operation would succeed if it was given the `passphrase` option.
666 - `keyName` -- `filename` that was given to `parseKey`
667 - `format` -- the `format` that was trying to parse the key (currently can only
670 ### `CertificateParseError`
672 The certificate data given could not be parsed as a valid certificate.
676 - `certName` -- `filename` that was given to `parseCertificate`
677 - `format` -- the `format` that was trying to parse the key
678 (see `parseCertificate`)
679 - `innerErr` -- the inner Error thrown by the format parser
684 * [`sshpk-agent`](https://github.com/arekinath/node-sshpk-agent) is a library
685 for speaking the `ssh-agent` protocol from node.js, which uses `sshpk`