Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions doc/api/crypto.md
Original file line number Diff line number Diff line change
Expand Up @@ -5338,6 +5338,75 @@ const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64);
console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653'
```

### `crypto.parsePKCS12(bundle[, options])`

<!-- YAML
added: REPLACEME
-->

* `bundle` {ArrayBuffer|Buffer|TypedArray|DataView} The DER-encoded PKCS#12
bundle.
* `options` {Object}
* `passphrase` {string|ArrayBuffer|Buffer|TypedArray|DataView} The passphrase
protecting the bundle. Omit for bundles with no passphrase. Omitting this
option is **not** equivalent to passing an empty string; the two are
handled differently, and a bundle created with one will not open with the
other.
Comment on lines +5529 to +5532

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not the behavior exposed by PKCS12_parse(). When given either nullptr or "", OpenSSL tries both PKCS#12 password encodings and uses whichever verifies the MAC. The tests already open the same ec.pfx once with "" and once with omission.

* Returns: {Object}
* `key` {KeyObject|null} The private key, or `null` if the bundle contains
none.
* `cert` {X509Certificate|null} The end-entity certificate, or `null` if the
bundle contains none.
* `ca` {X509Certificate\[]} Any additional certificates in the bundle, such
as intermediates and roots. May be empty.

Parses a PKCS#12 bundle — commonly seen with the `.p12` or `.pfx` extension —
and returns its contents.

```mjs
import { parsePKCS12 } from 'node:crypto';
import { readFileSync } from 'node:fs';
Comment thread
bmuenzenmeyer marked this conversation as resolved.

const { key, cert, ca } = parsePKCS12(
readFileSync('bundle.p12'),
{ passphrase: 'secret' },
);

console.log(cert.subject);
console.log(key.export({ type: 'pkcs8', format: 'pem' }));
```

```cjs
const { parsePKCS12 } = require('node:crypto');
const { readFileSync } = require('node:fs');

const { key, cert, ca } = parsePKCS12(
readFileSync('bundle.p12'),
{ passphrase: 'secret' },
);

console.log(cert.subject);
console.log(key.export({ type: 'pkcs8', format: 'pem' }));
```
Comment thread
panva marked this conversation as resolved.
Outdated

A PKCS#12 bundle may technically contain more than one private key. This API
returns only the first, matching the behavior of OpenSSL's `PKCS12_parse()`.

The end-entity certificate is identified by its association with the private
key. A bundle containing no private key therefore reports `cert` as `null` and
returns all of its certificates through `ca`.

Bundles encrypted with older algorithms — notably RC2 and PBE-SHA1 variants
produced by legacy Windows tooling and older versions of `keytool` — require
OpenSSL's legacy provider. Reading these throws an error with the code
[`ERR_CRYPTO_UNSUPPORTED_OPERATION`][]; starting Node.js with
[`--openssl-legacy-provider`][] may allow them to be read, subject to the
security implications of enabling that provider.

To use a PKCS#12 bundle directly for a TLS connection, prefer the `pfx` option
of [`tls.createSecureContext()`][] rather than parsing and re-supplying the
parts.

### `crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)`

<!-- YAML
Expand Down Expand Up @@ -7438,11 +7507,13 @@ See the [list of SSL OP Flags][] for details.
[`--enable-fips`]: cli.md#--enable-fips
[`--force-fips`]: cli.md#--force-fips
[`--openssl-config`]: cli.md#--openssl-configfile
[`--openssl-legacy-provider`]: cli.md#--openssl-legacy-provider
[`--openssl-shared-config`]: cli.md#--openssl-shared-config
[`BN_is_prime_ex`]: https://www.openssl.org/docs/man1.1.1/man3/BN_is_prime_ex.html
[`Buffer`]: buffer.md
[`DH_generate_key()`]: https://www.openssl.org/docs/man3.0/man3/DH_generate_key.html
[`DiffieHellmanGroup`]: #class-diffiehellmangroup
[`ERR_CRYPTO_UNSUPPORTED_OPERATION`]: errors.md#err_crypto_unsupported_operation
[`KeyObject`]: #class-keyobject
[`Sign`]: #class-sign
[`String.prototype.normalize()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize
Expand Down Expand Up @@ -7499,6 +7570,7 @@ See the [list of SSL OP Flags][] for details.
[`stream.Transform`]: stream.md#class-streamtransform
[`stream.Writable` options]: stream.md#new-streamwritableoptions
[`stream.transform` options]: stream.md#new-streamtransformoptions
[`tls.createSecureContext()`]: tls.md#tlscreatesecurecontextoptions
[`util.promisify()`]: util.md#utilpromisifyoriginal
[`verify.update()`]: #verifyupdatedata-inputencoding
[`verify.verify()`]: #verifyverifykey-signature-signatureencoding
Expand Down
2 changes: 2 additions & 0 deletions lib/crypto.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ const {
createSecretKey,
createPublicKey,
createPrivateKey,
parsePKCS12,
KeyObject,
} = require('internal/crypto/keys');
const {
Expand Down Expand Up @@ -206,6 +207,7 @@ module.exports = {
getHashes,
hkdf,
hkdfSync,
parsePKCS12,
pbkdf2,
pbkdf2Sync,
generateKeyPair,
Expand Down
54 changes: 54 additions & 0 deletions lib/internal/crypto/keys.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict';

const {
ArrayPrototypeMap,
ArrayPrototypeSlice,
ObjectDefineProperties,
ObjectPrototypeHasOwnProperty,
Expand Down Expand Up @@ -35,6 +36,7 @@ const {
kKeyEncodingPKCS8,
kKeyEncodingSPKI,
kKeyEncodingSEC1,
parsePKCS12: _parsePKCS12,
Comment thread
panva marked this conversation as resolved.
} = internalBinding('crypto');

const {
Expand Down Expand Up @@ -77,6 +79,8 @@ const {
isArrayBufferView,
} = require('internal/util/types');

const { Buffer } = require('buffer');

const {
fileURLToPath,
getURLHref,
Expand Down Expand Up @@ -739,6 +743,55 @@ function createPublicKey(key) {
return new PublicKeyObject(handle);
}

/**
* Parses a PKCS#12 (.p12 / .pfx) bundle. Returns an object holding the first
* private key as `key`, the certificate associated with it as `cert`, and any
* remaining certificates as an array in `ca`; `key` and `cert` are null when
* the bundle contains none.
* @param {ArrayBuffer|Buffer|TypedArray|DataView} bundle
* @param {object} [options]
* @returns {object}
*/
function parsePKCS12(bundle, options = kEmptyObject) {
if (!isArrayBufferView(bundle) && !isAnyArrayBuffer(bundle)) {
throw new ERR_INVALID_ARG_TYPE(
'bundle',
['ArrayBuffer', 'TypedArray', 'DataView', 'Buffer'],
bundle);
}

validateObject(options, 'options');
const { passphrase } = options;

// Absent and empty passphrases are distinct at the OpenSSL level and are
// kept distinct here. `undefined` means no passphrase; '' means a
// zero-length one.
let passBuf;
if (passphrase !== undefined) {
passBuf = getArrayBufferOrView(passphrase, 'options.passphrase', 'utf8');
// The binding reads the passphrase as a view; wrap a bare ArrayBuffer.
if (isAnyArrayBuffer(passBuf)) passBuf = Buffer.from(passBuf);
}

// Likewise, the binding reads the bundle as a view.
const bundleBuf = isAnyArrayBuffer(bundle) ? Buffer.from(bundle) : bundle;

const {
0: keyHandle,
1: certHandle,
2: caHandles,
} = _parsePKCS12(bundleBuf, passBuf);

// Required lazily: internal/crypto/x509 depends on this module.
const { InternalX509Certificate } = require('internal/crypto/x509');

return {
key: keyHandle === null ? null : new PrivateKeyObject(keyHandle),
cert: certHandle === null ? null : new InternalX509Certificate(certHandle),
ca: ArrayPrototypeMap(caHandles, (h) => new InternalX509Certificate(h)),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ca does not necessarily contain CA certificates or trust anchors; it contains every certificate other than the one matching the first private key. The certificate-only fixture even returns an end-entity certificate through ca. Could the result instead be { privateKey, certificate, additionalCertificates }?

};
}

/**
* Converts a secret KeyObjectHandle to a CryptoKey by dispatching to the
* algorithm-specific Web Crypto import path.
Expand Down Expand Up @@ -1333,6 +1386,7 @@ module.exports = {
createSecretKey,
createPublicKey,
createPrivateKey,
parsePKCS12,
KeyObject,
CryptoKey,
InternalCryptoKey,
Expand Down
2 changes: 2 additions & 0 deletions node.gyp
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,7 @@
'src/crypto/crypto_hash.cc',
'src/crypto/crypto_keys.cc',
'src/crypto/crypto_keygen.cc',
'src/crypto/crypto_pkcs12.cc',
'src/crypto/crypto_scrypt.cc',
'src/crypto/crypto_tls.cc',
'src/crypto/crypto_x509.cc',
Expand All @@ -425,6 +426,7 @@
'src/crypto/crypto_hash.h',
'src/crypto/crypto_keys.h',
'src/crypto/crypto_keygen.h',
'src/crypto/crypto_pkcs12.h',
'src/crypto/crypto_scrypt.h',
'src/crypto/crypto_tls.h',
'src/crypto/crypto_context.h',
Expand Down
Loading
Loading