文件加解密
Create a new projectEncrypt and decrypt textEncrypt and decrypt buffersEncrypt and decrypt streamsConclusion
Node.js provides a built-in module called
crypto
that you can use to encrypt and decrypt strings, numbers, buffers, streams, and more. This module offers cryptographic functionality that includes a set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions.In this article, you'll learn how to use Node.js
crypto
module to perform cryptographic operations on data. I'll show you how to encrypt data with a secret key and then decrypt it using the same secret key when required.For the sake of simplicity, I shall use AES (Advanced Encryption System) algorithm CTR encryption mode. Here is a good discussion on StackOverflow for choosing the correct AES encryption mode.
Create a new project
Create a new directory in your local file system and switch to it by typing the following:
Now execute the following command to initialize a new Node.js project:
The above command will create a new
package.json
file in the root directory. Make sure that you have already installed Node.js on your machine before issuing the above command.By default, the
crypto
module is already included in pre-built Node.js binaries. But if you have manually installed Node.js, crypto
may not be shipped with it. However, you can install it by executing the following command:Encrypt and decrypt text
Let us create the
crypto.js
file in the project's root directory and define our encryption and decryption functions as shown below:crpyto.js
The following example demonstrates how you can encrypt and decrypt text data (strings, numbers, etc.) by using the above functions:
crpyto-text.js
Encrypt and decrypt buffers
You can also encrypt and decrypt buffers by using the functions defined above. Just pass the buffer in place of the string, and it should work:
crpyto-buffer.js
Encrypt and decrypt streams
You can also encrypt and decrypt streams by using the
crypto
module, as shown in the following example:crpyto-stream.js
Source Code: Download the complete source code of this project from GitHub, available under the MIT license.
Conclusion
In this article, we looked at how to perform cryptographic operations on text, buffers, and streams using the Node.js built-in crypto module. This is extremely useful if you need to encrypt sensitive data like secret keys before storing them in a database.
Loading...