A private key was not found for a certificate.
Production Risk
Low. This is a server startup error that prevents the service from listening for connections, so it is always caught before going live.
This error occurs in TLS/SSL contexts when a certificate is provided without a corresponding private key. A secure server needs both a public certificate to send to clients and a private key to decrypt their messages. This error indicates the private key is missing from the secure context.
- 1Providing a certificate to `tls.createSecureContext()` but omitting the `key`.
- 2The private key is in an incorrect format or is password-protected and no passphrase was provided.
- 3File system errors preventing the private key file from being read.
This error is thrown when a secure context is being created for a TLS server or client, and the provided certificate cannot be paired with a valid private key.
const tls = require('tls');
const myCert = '...'; // Contents of a PEM certificate
try {
// The 'key' option is missing.
tls.createSecureContext({ cert: myCert });
} catch (err) {
console.error(err.code);
}expected output
ERR_CRYPTO_KEY_NOT_FOUND
Fix
Provide Both Certificate and Key
WHEN Creating a secure TLS context.
const tls = require('tls');
const fs = require('fs');
const options = {
cert: fs.readFileSync('path/to/cert.pem'),
key: fs.readFileSync('path/to/key.pem')
};
const secureContext = tls.createSecureContext(options);Why this works
When creating a `tls.Server` or `https.Server`, ensure that the options object contains both the `cert` (public certificate) and the `key` (private key).
const tls = require('tls');
const myCert = '...'; // Contents of a PEM certificate
try {
// The 'key' option is missing.
tls.createSecureContext({ cert: myCert }); // this triggers ERR_CRYPTO_KEY_NOT_FOUNDtry {
// operation that may throw ERR_CRYPTO_KEY_NOT_FOUND
riskyOperation()
} catch (err) {
if (err.code === 'ERR_CRYPTO_KEY_NOT_FOUND') {
console.error('ERR_CRYPTO_KEY_NOT_FOUND:', err.message)
} else {
throw err
}
}// Validate inputs before calling the operation
function safe_err_crypto_key_not_found(...args) {
// validate args here
return performOperation(...args)
}✕
https://github.com/nodejs/node/blob/main/src/crypto/crypto_tls.cc
More information ↗Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev