What is the createPrivateKey() method in Node.js?

The createPrivateKey method comes with the crypto module and is used to generate a private key that is used in decrypting or deciphering a message that has been encrypted by a public key. The private and public keys are mathematically related, but the private key cant be easily generated from the public key.

Syntax

To use the createPrivateKey method, we need to load in the crypto module. The following syntax is used for the createPrivateKey method:

crypto.createPrivateKey(key)

Parameter

The createPrivateKey method takes in one parameter, which can be an object that takes in the following properties:

  • Key: This could be a string and can also be in either a PEM, DER OR JWK format.
  • Format: PEM, DER or JWK. The default format is PEM.
  • Passphrase: A string that is used for decryption.
  • Encoding: An encoding format for the key if the key is a string i.e Base64 encoding format.

DER format is a purely binary format. DER-encoded content can’t be inspected with a text editor and can’t be copied and pasted easily.

PEM is a Base64 encoded version of DER that makes it easier for it to be copied and pasted.

Return value

The createPrivateKey method returns a key object, which is a class used to represent symmetric or asymmetric keys.

Example

The following code snippet demonstrates how to use the createPrivateKey method to return a key object. Note that only the key property is compulsory while the rest of the properties are optional.

The start and end lines of the input string must be specified. Also, a passphrase needs to be specified if the private key is encrypted. Passphrase length is limited to 1024 bytes.

  • JavaScript

Free Resources