Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
63 changes: 63 additions & 0 deletions doc/api/crypto.md
Original file line number Diff line number Diff line change
Expand Up @@ -5516,6 +5516,65 @@ 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. PKCS#12
encodes an absent and an empty passphrase differently, but OpenSSL tries
both, so omitting this option and passing `''` behave the same. The
passphrase must not contain a NUL byte; PKCS#12 passwords cannot
represent one, and passing one throws [`ERR_INVALID_ARG_VALUE`][].
* Returns: {Object}
* `privateKey` {KeyObject|null} The private key, or `null` if the bundle
contains none.
* `certificate` {X509Certificate|null} The certificate associated with
`privateKey`, or `null` if the bundle contains none.
* `additionalCertificates` {X509Certificate\[]} Every other certificate in
the bundle. These are not necessarily certificate authorities; this is
whatever remains once `certificate` has been taken out. 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';

const { privateKey, certificate } = parsePKCS12(
readFileSync('bundle.p12'),
{ passphrase: 'secret' },
);

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

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()`.

`certificate` is identified by its association with the private key. A bundle
containing no private key therefore reports `certificate` as `null` and returns
all of its certificates through `additionalCertificates`, including any
end-entity certificate the bundle holds.

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 @@ -7624,11 +7683,14 @@ 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
[`ERR_INVALID_ARG_VALUE`]: errors.md#err_invalid_arg_value
[`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 @@ -7690,6 +7752,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 @@ -216,6 +217,7 @@ module.exports = {
getMacs,
hkdf,
hkdfSync,
parsePKCS12,
pbkdf2,
pbkdf2Sync,
generateKeyPair,
Expand Down
66 changes: 66 additions & 0 deletions lib/internal/crypto/keys.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
'use strict';

const {
ArrayPrototypeMap,
ArrayPrototypeSlice,
ObjectDefineProperties,
ObjectPrototypeHasOwnProperty,
ObjectSetPrototypeOf,
StringPrototypeIncludes,
StringPrototypeStartsWith,
SymbolToStringTag,
TypedArrayPrototypeIncludes,
Uint8Array,
} = primordials;

Expand Down Expand Up @@ -35,6 +37,7 @@ const {
kKeyEncodingPKCS8,
kKeyEncodingSPKI,
kKeyEncodingSEC1,
parsePKCS12: _parsePKCS12,
} = internalBinding('crypto');

const {
Expand Down Expand Up @@ -63,6 +66,7 @@ const {

const {
getArrayBufferOrView,
getBufferSourceBytes,
bigIntArrayToUnsignedBigInt,
normalizeAlgorithm,
hasAnyNotIn,
Expand All @@ -77,6 +81,8 @@ const {
isArrayBufferView,
} = require('internal/util/types');

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

const {
fileURLToPath,
getURLHref,
Expand Down Expand Up @@ -757,6 +763,65 @@ function createPublicKey(key) {
return new PublicKeyObject(handle);
}

/**
* Parses a PKCS#12 (.p12 / .pfx) bundle. Returns an object holding the first
* private key as `privateKey`, the certificate associated with it as
* `certificate`, and every other certificate in the bundle as an array in
* `additionalCertificates`. `privateKey` and `certificate` 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;

// `undefined` means no passphrase, '' a zero-length one. OpenSSL accepts
// either PKCS#12 password encoding for both, so they behave the same.
let passBuf;
if (passphrase !== undefined) {
passBuf = getArrayBufferOrView(passphrase, 'options.passphrase', 'utf8');
// OpenSSL takes the passphrase as a NUL-terminated C string, so one
// containing a NUL byte would be truncated there and the bundle opened
// with only the bytes before it. A PKCS#12 password cannot represent an
// embedded NUL anyway, so reject it outright.
if (TypedArrayPrototypeIncludes(getBufferSourceBytes(passBuf), 0)) {
throw new ERR_INVALID_ARG_VALUE(
'options.passphrase', passphrase, 'must not contain null bytes');
}
// 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: otherHandles,
} = _parsePKCS12(bundleBuf, passBuf);

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

return {
privateKey: keyHandle === null ? null : new PrivateKeyObject(keyHandle),
certificate:
certHandle === null ? null : new InternalX509Certificate(certHandle),
additionalCertificates:
ArrayPrototypeMap(otherHandles, (h) => new InternalX509Certificate(h)),
};
}

/**
* Converts a secret KeyObjectHandle to a CryptoKey by dispatching to the
* algorithm-specific Web Crypto import path.
Expand Down Expand Up @@ -1358,6 +1423,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 @@ -409,6 +409,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 @@ -429,6 +430,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