{"id":4891,"date":"2023-10-17T14:16:17","date_gmt":"2023-10-17T08:46:17","guid":{"rendered":"https:\/\/codeforgeek.com\/?p=4891"},"modified":"2024-11-21T15:53:59","modified_gmt":"2024-11-21T10:23:59","slug":"encrypt-and-decrypt-data-in-node-js","status":"publish","type":"post","link":"https:\/\/codeforgeek.com\/encrypt-and-decrypt-data-in-node-js\/","title":{"rendered":"Encrypt and Decrypt Data in Node.js Using Crypto: A Step-by-Step Guide"},"content":{"rendered":"\n<p>In Node.js we perform a lot of operations on data, which involves transferring data simultaneously from server to client and from client to server. There may be a possibility of a data breach while transferring data. To avoid this we can encrypt the data and then decrypt it later to get the same output ensuring data integrity.<\/p>\n\n\n\n<p>In this article, we will learn about the Node.js Crypto Module used to encrypt and decrypt data. We will learn how to do encryption and decryption using cryptography techniques for both string and buffer data. Let&#8217;s get started.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Node.js Crypto Module<\/h2>\n\n\n\n<p>Node.js includes a built-in module called<strong> &#8216;crypto&#8217; <\/strong>which you can use to perform cryptographic operations on data. You can do cryptographic operations on strings, buffers, and streams. This includes encrypting, decrypting, hashing, etc. You can also use various encryption algorithms when using the <strong>&#8216;crypto&#8217;<\/strong> module. <a href=\"https:\/\/nodejs.org\/api\/crypto.html\" data-type=\"link\" data-id=\"https:\/\/nodejs.org\/api\/crypto.html\" target=\"_blank\" rel=\"noopener\">Click here<\/a> to get the list. For this article, we will be using AES (Advanced Encryption System) algorithm.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Install Crypto Module<\/h3>\n\n\n\n<p>If you have installed Node.js by manual build then there is a chance that the<strong> &#8216;crypto&#8217;<\/strong> is not shipped with it. You can run this command to install the &#8216;<strong>crypto&#8217;<\/strong> dependency.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nnpm install crypto --save\n<\/pre><\/div>\n\n\n<p><em>You don&#8217;t need to do that if you have installed it using pre-built packages.<\/em><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Encrypt and Decrypt Data in Node.js<\/h2>\n\n\n\n<p>Let&#8217;s now write code for encrypting and decrypting data. Let&#8217;s start with a basic setup.<\/p>\n\n\n\n<p><strong>Step 1:<\/strong> Create a new folder &amp; open it on the code editor.<\/p>\n\n\n\n<p><strong>Step 2:<\/strong> Create a file &#8216;<strong>aap.js&#8217;<\/strong> inside that folder.<\/p>\n\n\n\n<p><strong>Step 3: <\/strong>Open the terminal &amp; type the below command. This initializes the Node Packages Manager, by which we can install any Node.js framework.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nnpm init -y\n<\/pre><\/div>\n\n\n<p><strong>Step 4: <\/strong>Inside the terminal, type the below command to install <strong>&#8216;crypto&#8217;<\/strong> as a dependency in the project folder.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nnpm install crypto --save\n<\/pre><\/div>\n\n\n<p><strong>Step 5: <\/strong>Open the &#8216;<strong>app.js&#8217;<\/strong> file and write the following code for data encryption and decryption.<\/p>\n\n\n\n<p><strong><em>app.js<\/em><\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nconst crypto = require(&#039;crypto&#039;); \/\/ Import the crypto module\nconst algorithm = &#039;aes-256-cbc&#039;; \/\/ Use AES 256-bit encryption\nconst key = crypto.randomBytes(32); \/\/ Generate a random 32-byte key\nconst iv = crypto.randomBytes(16); \/\/ Generate a random 16-byte IV\n\nfunction encrypt(data) { \/\/ Function to encrypt data\n    let cipher = crypto.createCipheriv(&#039;aes-256-cbc&#039;, Buffer.from(key), iv);\n    let encrypted = cipher.update(data);\n    encrypted = Buffer.concat(&#x5B;encrypted, cipher.final()]);\n    return {\n        iv: iv.toString(&#039;hex&#039;),\n        encryptedData: encrypted.toString(&#039;hex&#039;)\n    };\n}\n\nfunction decrypt(data) { \/\/ Function to decrypt data\n    let iv = Buffer.from(data.iv, &#039;hex&#039;);\n    let encryptedText = Buffer.from(data.encryptedData, &#039;hex&#039;);\n    let decipher = crypto.createDecipheriv(&#039;aes-256-cbc&#039;, Buffer.from(key), iv);\n    let decrypted = decipher.update(encryptedText);\n    decrypted = Buffer.concat(&#x5B;decrypted, decipher.final()]);\n    return decrypted.toString();\n}\n\nvar data = &quot;Username &amp; Password&quot; \/\/ Data to be encrypted\n\nvar encrypted = encrypt(data); \/\/ Encrypt the data\nconsole.log(&quot;Encrypt Data: &quot;, encrypted)\n\nvar decrypted = decrypt(encrypted); \/\/ Decrypt the data\nconsole.log(&quot;Decrypt Data: &quot;, decrypted)\n<\/pre><\/div>\n\n\n<p><strong>Explanation:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>First, we have imported the &#8216;<strong>crypto&#8217;<\/strong> module using<strong> require()<\/strong>.<\/li>\n\n\n\n<li>Then we have defined an encryption algorithm to use for encryption. We have used <strong>AES <\/strong>(Advanced Encryption Standard) with a <strong>256-bit<\/strong> key length in <strong>CBC<\/strong> (Cipher Block Chaining) mode.<\/li>\n\n\n\n<li>Then we used the <strong>randomBytes()<\/strong> function to generate a random 32-byte secret key.<\/li>\n\n\n\n<li>Then we used the same method to generate a random 16-byte<strong> IV<\/strong> ( Initialization Vector).<\/li>\n\n\n\n<li>Then we have defined a function<strong> &#8216;encrypt&#8217; <\/strong>that takes raw data, encodes it and returns the encrypted one using the <strong>crypto <\/strong>module.<\/li>\n\n\n\n<li>Similarly, we have defined another function &#8216;<strong>decrypt&#8217;<\/strong> to decrypt the encrypted data.<\/li>\n\n\n\n<li>At last, we passed the plaintext having some random data to <strong>encrypt() <\/strong>functions and then converted ciphertext to <strong>decrypt()<\/strong> to see the results.<\/li>\n<\/ul>\n\n\n\n<p><strong>Run the Application<\/strong><\/p>\n\n\n\n<p>The code is written in a single file <strong>&#8216;app.js&#8217;<\/strong> that runs on executing the below command in the terminal.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nnode app.js\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><img decoding=\"async\" width=\"1024\" height=\"543\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2023\/10\/encrypt-decrpyt-string-1024x543.png\" alt=\"Encrypt Decrpyt Data\" class=\"wp-image-23059\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2023\/10\/encrypt-decrpyt-string-1024x543.png 1024w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2023\/10\/encrypt-decrpyt-string-300x159.png 300w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2023\/10\/encrypt-decrpyt-string-768x407.png 768w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2023\/10\/encrypt-decrpyt-string-1536x814.png 1536w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2023\/10\/encrypt-decrpyt-string.png 1920w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Encrypt and Decrypt Buffer in Node.js<\/h2>\n\n\n\n<p>In the above section, we have done encryption and decryption of a string. To encrypt and decrypt buffers, you can simply pass the buffer in place of the string during the function call and it will encrypt and decrypt it accordingly.<\/p>\n\n\n\n<p><strong><em>app.js<\/em><\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nconst crypto = require(&#039;crypto&#039;); \/\/ Import the crypto module\nconst algorithm = &#039;aes-256-cbc&#039;; \/\/ Use AES 256-bit encryption\nconst key = crypto.randomBytes(32); \/\/ Generate a random 32-byte key\nconst iv = crypto.randomBytes(16); \/\/ Generate a random 16-byte IV\n\nfunction encrypt(data) { \/\/ Function to encrypt data\n    let cipher = crypto.createCipheriv(&#039;aes-256-cbc&#039;, Buffer.from(key), iv);\n    let encrypted = cipher.update(data);\n    encrypted = Buffer.concat(&#x5B;encrypted, cipher.final()]);\n    return {\n        iv: iv.toString(&#039;hex&#039;),\n        encryptedData: encrypted.toString(&#039;hex&#039;)\n    };\n}\n\nfunction decrypt(data) { \/\/ Function to decrypt data\n    let iv = Buffer.from(data.iv, &#039;hex&#039;);\n    let encryptedText = Buffer.from(data.encryptedData, &#039;hex&#039;);\n    let decipher = crypto.createDecipheriv(&#039;aes-256-cbc&#039;, Buffer.from(key), iv);\n    let decrypted = decipher.update(encryptedText);\n    decrypted = Buffer.concat(&#x5B;decrypted, decipher.final()]);\n    return decrypted.toString();\n}\n\nvar data = &quot;Username &amp; Password&quot; \/\/ Data to be encrypted\n\nvar buffer = Buffer.from(data); \/\/ Convert the data to a buffer\n\nvar encrypted = encrypt(buffer); \/\/ Encrypt the data\n\nconsole.log(encrypted);\n\nvar decrypted = decrypt(encrypted); \/\/ Decrypt the data\nconsole.log(decrypted);\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><img decoding=\"async\" width=\"1024\" height=\"545\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2023\/10\/encrypt-decrpyt-buffer-1-1024x545.png\" alt=\"Encrypt Decrpyt Buffer\" class=\"wp-image-23061\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2023\/10\/encrypt-decrpyt-buffer-1-1024x545.png 1024w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2023\/10\/encrypt-decrpyt-buffer-1-300x160.png 300w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2023\/10\/encrypt-decrpyt-buffer-1-768x408.png 768w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2023\/10\/encrypt-decrpyt-buffer-1-1536x817.png 1536w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2023\/10\/encrypt-decrpyt-buffer-1.png 1918w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p>You can also pipe the streams into the encrypt() function to have secure encrypted data passing through the streams.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>In this article, we have discovered the <strong>crypto <\/strong>module provides different functions for performing encryption and decryption in Node.js applications. This is done in order to secure data, to protect sensitive data from malicious parties. We can use this module to convert plain text into unreadable text and vice versa. We can either encrypt &amp; decrypt both plain text or buffer data. Hope you have enjoyed reading the content. Check out more interesting articles on NodeJS below.<\/p>\n\n\n\n<p><strong>Read More:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/codeforgeek.com\/refresh-token-jwt-nodejs-authentication\/\">Nodejs Authentication Using JWT and Refresh Token<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/codeforgeek.com\/nodejs-tls-ssl\/\">NodeJS TLS\/SSL &#8211; Secure Your Network Connections<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Reference&nbsp;<\/h2>\n\n\n\n<p><a href=\"https:\/\/stackoverflow.com\/questions\/6953286\/how-to-encrypt-data-that-needs-to-be-decrypted-in-node-js\" target=\"_blank\" rel=\"noopener\">How to encrypt data that needs to be decrypted in node.js?<\/a><\/p>\n\n\n\n<p><a href=\"https:\/\/codeforgeek.com\/the-role-of-ai-in-simplifying-coding-processes\/\">Read the article<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In Node.js we perform a lot of operations on data, which involves transferring data simultaneously from server to client and from client to server. There may be a possibility of a data breach while transferring data. To avoid this we can encrypt the data and then decrypt it later to get the same output ensuring [&hellip;]<\/p>\n","protected":false},"author":79,"featured_media":23063,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_surecart_dashboard_logo_width":"180px","_surecart_dashboard_show_logo":true,"_surecart_dashboard_navigation_orders":true,"_surecart_dashboard_navigation_invoices":true,"_surecart_dashboard_navigation_subscriptions":true,"_surecart_dashboard_navigation_downloads":true,"_surecart_dashboard_navigation_billing":true,"_surecart_dashboard_navigation_account":true,"_uag_custom_page_level_css":"","footnotes":""},"categories":[14],"tags":[],"class_list":["post-4891","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-nodejs"],"blocksy_meta":[],"uagb_featured_image_src":{"full":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2023\/10\/Encrypt-and-Decrypt-Data.jpg",1000,600,false],"thumbnail":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2023\/10\/Encrypt-and-Decrypt-Data-150x150.jpg",150,150,true],"medium":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2023\/10\/Encrypt-and-Decrypt-Data-300x180.jpg",300,180,true],"medium_large":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2023\/10\/Encrypt-and-Decrypt-Data-768x461.jpg",768,461,true],"large":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2023\/10\/Encrypt-and-Decrypt-Data.jpg",1000,600,false],"1536x1536":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2023\/10\/Encrypt-and-Decrypt-Data.jpg",1000,600,false],"2048x2048":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2023\/10\/Encrypt-and-Decrypt-Data.jpg",1000,600,false]},"uagb_author_info":{"display_name":"Aditya Gupta","author_link":"https:\/\/codeforgeek.com\/author\/aditya\/"},"uagb_comment_info":0,"uagb_excerpt":"In Node.js we perform a lot of operations on data, which involves transferring data simultaneously from server to client and from client to server. There may be a possibility of a data breach while transferring data. To avoid this we can encrypt the data and then decrypt it later to get the same output ensuring&hellip;","_links":{"self":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/posts\/4891","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/users\/79"}],"replies":[{"embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/comments?post=4891"}],"version-history":[{"count":0,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/posts\/4891\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/media\/23063"}],"wp:attachment":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/media?parent=4891"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/categories?post=4891"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/tags?post=4891"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}