crypto.publicencrypt() method in Node.js1 Mar 2025 | 3 min read In this article, we will discuss the crypto.publicencrypt() method in Node.js with its syntax, parameters, and example. What is the crypto.publicencrypt() method in Node.js?The crypto.publicEncrypt() method is an integrated application programming interface (API) of the Node.js crypto module. It encrypts a buffer's defined content using a given public key. This method ensures that only the holder of the corresponding private key can decrypt the encrypted data. The method supports different hash functions and padding schemes. For best security, use crypto.constants.RSA_PKCS1_OAEP_PADDING with a hash function like SHA-256. Crypto.publicEncrypt () returns the encrypted data in raw binary format as a Buffer upon calling it. The base64 encoding can be applied to make the handling and transmission of this data easier. Compatibility with several key types, including strings, buffers, and KeyObjects, is a significant feature of crypto.publicEncrypt(). It provides additional options, including OAEP labels, for further encryption customization. Syntax:It has the following syntax: Parameters:
There are various formats available for this parameter:
Return Value:When using the crypto.publicEncrypt() function, the encrypted content is returned in a new buffer. Once the original data has been encrypted with the given public key, this buffer acts as the representation of the ciphertext. Example:Let us take an example to illustrate the crypto.publicEncrypt() function in Node.js. Output: Error writing public key file: EACCES: permission denied, open '/public_key.pem' Explanation:This Node.js script provides an example of creating RSA key pairs and encrypting data. The path, fs, and crypto modules are included initially. To handle any errors that may arise during file operations, the generateKeyFiles function generates a 2048-bit RSA key pair and saves it to public_key.pem. The RSA OAEP padding and SHA-256 hashing of a specified plaintext string are performed by the encryptString function, which reads this public key. Next, for readability, the script encrypts the string "Hii All!" and prints the raw buffer along with its base64-encoded version. In the case of an error, our code provides helpful feedback and gracefully handles faults while ensuring secure encryption using RSA. |
We request you to subscribe our newsletter for upcoming updates.

We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India