What is Node crypto.createPrivateKey(key)?
crypto.createPrivateKey is a function that accepts one argument and returns a new key (object(KeyObject)) that contains a private key.
crypto.createPrivateKey(key)
The
crypto.createPrivatekeyfunction was added in node version 11.6.0, earlier versions of node don’t support this function.
Parameter
If the key is not a string or buffer, then the key must be an object with the following properties.
- key: The key material can either be in the PEM, DER, or JWK format. Key can be an instance of any of the following:
stringArrayBufferBufferTypedArrayDataViewObject
- format : Must be
,pem privacy-enhanced mail , order distinguished encoding rules . The Default format isjwk json web key pemand the format must be astring. - type : Must be
,pkcs1 public key cryptographic standards 1 , orpkcs8 public key cryptographic standards 8 . This option is only required if the format issec1 standards for efficient cryptography 1 der; otherwise, it is ignored. The type must be astring. - passphrase : Passphrase is used for decryption. If the private key is encrypted, a passphrase must be specified. The length of the passphrase is limited to 1024 bytes. Passphrase must be either a
stringorBuffer. - encoding : The string encoding to be used when key is a string.
Return value
The crypto.createPrivateKey function returns a new Key Object.
Example
The code snippet below shows how to use the crypto.createPrivateKey function.
The createPrivateKey function uses the key argument to create and return a new key object.
const crypto = require("crypto");//generate encrypted privateKeyconst {publicKey, privateKey } = crypto.generateKeyPairSync('rsa',{modulusLength: 4096,publicKeyEncoding: {type: 'spki',format: 'pem'},privateKeyEncoding: {type: 'pkcs8',format: 'pem',cipher: 'aes-256-cbc',passphrase: ''}});//generate key Objectconst keyObject = crypto.createPrivateKey({key: privateKey,format: "pem",type: "pkcs1",passphrase: "",encoding: "utf-8"});export default keyObject;
Explanation
- Import crypto module.
- Use the
crypto.generateKeyPairSyncfunction to synchronously getprivateKey.
- Finally, pass the private key generated from the
crypto.generateKeyPairSyncto thecrypto.createPrivateKeyfunction. This, in turn, returns akeyObject. - The last line exports the
keyObject; thus, making it available for use on other modules.
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved