<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mihir Shah on Medium]]></title>
        <description><![CDATA[Stories by Mihir Shah on Medium]]></description>
        <link>https://medium.com/@mihirshahwrites?source=rss-9ced4661f27b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XZgcw6C3Kacnc9AwWsDw3A.jpeg</url>
            <title>Stories by Mihir Shah on Medium</title>
            <link>https://medium.com/@mihirshahwrites?source=rss-9ced4661f27b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 17:32:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mihirshahwrites/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building Production-Grade AI Chat Features in React: The Architecture Nobody Talks About]]></title>
            <link>https://medium.com/@mihirshahwrites/building-production-grade-ai-chat-features-in-react-the-architecture-nobody-talks-about-2ef1b5d1b63c?source=rss-9ced4661f27b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ef1b5d1b63c</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Mihir Shah]]></dc:creator>
            <pubDate>Wed, 03 Dec 2025 15:40:42 GMT</pubDate>
            <atom:updated>2025-12-03T15:40:42.991Z</atom:updated>
            <content:encoded><![CDATA[<p>In the era of AI-driven applications, developers often integrate sophisticated language models into their projects. Among these, OpenAI’s API stands as a powerful gateway to cutting-edge NLP capabilities. This guide explores how to seamlessly integrate OpenAI’s API within your React applications through a production-ready architectural pattern.</p><h3>Understanding the Integration Challenge</h3><p>Integrating external APIs into React applications requires careful consideration of several aspects: state management, error handling, request lifecycle management, and security. The OpenAI API, while straightforward in its REST interface, presents unique challenges when integrated with React’s component lifecycle and concurrent rendering model.</p><p>The conventional approach of making API calls directly from components often leads to race conditions, memory leaks, and difficult-to-debug issues. Instead, we’ll explore a refined architecture that leverages React’s modern patterns and best practices.</p><h3>Architecture Overview</h3><p>The recommended pattern involves four key layers:</p><p>• <strong>Custom Hooks Layer:</strong> Encapsulates API interaction logic<br>• <strong>Context Layer:</strong> Manages application-wide state<br>• <strong>Error Handling Layer:</strong> Gracefully manages failures<br>• <strong>Component Layer:</strong> Consumes processed data</p><p>This separation ensures your application remains scalable, testable, and maintainable as complexity grows.</p><h3>Setting Up the OpenAI Configuration</h3><p>Begin by installing the OpenAI library.</p><pre>npm install openai</pre><p>Create a configuration file to securely manage your API credentials.</p><pre>// config/openai.config.js<br>export const openaiConfig = {<br>  apiKey: process.env.REACT_APP_OPENAI_API_KEY,<br>  model: &#39;gpt-3.5-turbo&#39;,<br>  maxTokens: 1000,<br>  temperature: 0.7,<br>};</pre><h3>Building the Custom Hook</h3><p>Craft a reusable hook that encapsulates API interaction logic.</p><pre>// hooks/useOpenAI.js<br>import { useState, useCallback } from &#39;react&#39;;<br>import { OpenAI } from &#39;openai&#39;;<br>import { openaiConfig } from &#39;../config/openai.config&#39;;<br><br>export const useOpenAI = () =&gt; {<br>  const [loading, setLoading] = useState(false);<br>  const [error, setError] = useState(null);<br>  const [data, setData] = useState(null);<br><br>  const client = new OpenAI({<br>    apiKey: openaiConfig.apiKey,<br>    dangerouslyAllowBrowser: true, // Only for development<br>  });<br><br>  const generateCompletion = useCallback(async (prompt) =&gt; {<br>    setLoading(true);<br>    setError(null);<br><br>    try {<br>      const response = await client.chat.completions.create({<br>        model: openaiConfig.model,<br>        messages: [<br>          {<br>            role: &#39;user&#39;,<br>            content: prompt,<br>          },<br>        ],<br>        max_tokens: openaiConfig.maxTokens,<br>        temperature: openaiConfig.temperature,<br>      });<br><br>      const content = response.choices[0].message.content;<br>      setData(content);<br>      return content;<br>    } catch (err) {<br>      const errorMessage = err.response?.data?.error?.message || err.message;<br>      setError(errorMessage);<br>      console.error(&#39;OpenAI API Error:&#39;, errorMessage);<br>      throw err;<br>    } finally {<br>      setLoading(false);<br>    }<br>  }, []);<br><br>  return { generateCompletion, loading, error, data };<br>};</pre><h3>Implementing Context for State Management</h3><p>Create a context provider to distribute OpenAI functionality across your application.</p><pre>// context/OpenAIContext.js<br>import React, { createContext, useContext } from &#39;react&#39;;<br>import { useOpenAI } from &#39;../hooks/useOpenAI&#39;;<br><br>export const OpenAIContext = createContext();<br><br>export const OpenAIProvider = ({ children }) =&gt; {<br>  const openaiMethods = useOpenAI();<br><br>  return (<br>    &lt;OpenAIContext.Provider value={openaiMethods}&gt;<br>      {children}<br>    &lt;/OpenAIContext.Provider&gt;<br>  );<br>};<br><br>export const useOpenAIContext = () =&gt; {<br>  const context = useContext(OpenAIContext);<br>  if (!context) {<br>    throw new Error(&#39;useOpenAIContext must be used within OpenAIProvider&#39;);<br>  }<br>  return context;<br>};</pre><h3>Consuming in Components</h3><p>Now implement your UI component that leverages this infrastructure:</p><pre>// components/ChatInterface.jsx<br>import React, { useState } from &#39;react&#39;;<br>import { useOpenAIContext } from &#39;../context/OpenAIContext&#39;;<br><br>export const ChatInterface = () =&gt; {<br>  const [input, setInput] = useState(&#39;&#39;);<br>  const { generateCompletion, loading, error, data } = useOpenAIContext();<br><br>  const handleSubmit = async (e) =&gt; {<br>    e.preventDefault();<br>    if (!input.trim()) return;<br><br>    try {<br>      await generateCompletion(input);<br>      setInput(&#39;&#39;);<br>    } catch (err) {<br>      console.error(&#39;Failed to generate completion:&#39;, err);<br>    }<br>  };<br><br>  return (<br>    &lt;div className=&quot;chat-interface&quot;&gt;<br>      &lt;form onSubmit={handleSubmit}&gt;<br>        &lt;textarea<br>          value={input}<br>          onChange={(e) =&gt; setInput(e.target.value)}<br>          placeholder=&quot;Enter your prompt...&quot;<br>          disabled={loading}<br>        /&gt;<br>        &lt;button type=&quot;submit&quot; disabled={loading}&gt;<br>          {loading ? &#39;Processing...&#39; : &#39;Send&#39;}<br>        &lt;/button&gt;<br>      &lt;/form&gt;<br><br>      {error &amp;&amp; (<br>        &lt;div className=&quot;error-message&quot; role=&quot;alert&quot;&gt;<br>          {error}<br>        &lt;/div&gt;<br>      )}<br><br>      {data &amp;&amp; (<br>        &lt;div className=&quot;response-container&quot;&gt;<br>          &lt;p&gt;{data}&lt;/p&gt;<br>        &lt;/div&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>};</pre><h3>Security Considerations</h3><p><strong>Critical</strong>: Never expose your API key directly in your code or commit it to version control. Use environment variables exclusively:</p><pre># .env.local (never commit this file)<br>REACT_APP_OPENAI_API_KEY=your-api-key-here</pre><p>For production deployments, consider implementing a backend proxy that handles API calls server-side, adding an extra layer of security.</p><h3>Best Practices Summary</h3><ul><li><strong>Request Debouncing</strong>: Implement debouncing for frequently triggered requests to minimize API costs</li><li><strong>Response Caching</strong>: Cache responses to reduce redundant API calls</li><li><strong>Rate Limiting</strong>: Implement client-side rate limiting to respect API quotas</li><li><strong>User Feedback</strong>: Provide clear loading states and error messages</li><li><strong>TypeScript</strong>: Consider adopting TypeScript for improved type safety</li><li><strong>Testing</strong>: Write comprehensive tests for your hooks and components</li></ul><h3>Conclusion</h3><p>Integrating OpenAI’s API into React applications doesn’t require reinventing the wheel. By following architectural patterns that respect React’s design principles and implementing proper error handling, you create applications that are robust, maintainable, and user-friendly.</p><p>The approach outlined in this guide provides a solid foundation that scales from simple prototypes to complex production applications. As you extend this architecture, remember that clarity and separation of concerns are your allies in managing complexity.</p><p>Start small, test thoroughly, and iterate as your requirements evolve. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ef1b5d1b63c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step-by-Step Installation Guide for Creating a Runnable Full Stack Web Application with Database…]]></title>
            <link>https://medium.com/@mihirshahwrites/step-by-step-installation-guide-for-creating-a-runnable-full-stack-web-application-with-database-925f0372f801?source=rss-9ced4661f27b------2</link>
            <guid isPermaLink="false">https://medium.com/p/925f0372f801</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Mihir Shah]]></dc:creator>
            <pubDate>Mon, 17 Jul 2023 15:32:19 GMT</pubDate>
            <atom:updated>2023-07-17T17:19:57.747Z</atom:updated>
            <content:encoded><![CDATA[<h3>Step-by-Step Installation Guide for Creating a Runnable Full Stack Web Application with Database Connection</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*3Q83qznHRGmI8-UKU61PBw.png" /></figure><h4><strong>Introduction</strong></h4><p>This installation guide will walk you through the step-by-step process of creating a new runnable full stack web application with a database connection. We’ll cover the setup of both the frontend and backend components, along with connecting to a database and running the application locally.</p><h4>Prerequisites</h4><p>Before we begin, ensure that you have the following prerequisites installed:</p><ol><li>Node.js and npm (Node Package Manager) are installed on your system.</li><li>A code editor or IDE of your choice.</li><li>A database system installed and running (e.g., MySQL, PostgreSQL, MongoDB).</li></ol><h4>Step 1: Setting Up the Backend (Node.js and Express)</h4><ol><li>Create a new directory for your backend project.</li><li>Open a terminal or command prompt and navigate to the newly created directory.</li><li>Initialize a new Node.js project using the command: npm init.</li><li>Install the necessary dependencies by running the following: npm install express.</li></ol><h4>Step 2: Creating the Backend Server and Database Connection</h4><ol><li>Create a new file called index.js in your backend directory.</li><li>Open index.js in your code editor and add the following code:</li></ol><pre>const express = require(&#39;express&#39;);<br>const app = express();<br>const port = 3000;<br><br>// Add the database connection setup<br>const database = require(&#39;./database&#39;);<br>database.connect(); // Assuming you have a separate file for the database connection setup<br><br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>  res.send(&#39;Hello from the backend!&#39;);<br>});<br><br>app.listen(port, () =&gt; {<br>  console.log(`Backend server is running on port ${port}`);<br>});</pre><ol><li>Create a new file called database.js in your backend directory.</li><li>Open database.js in your code editor and add the following code:</li></ol><pre>// Add the necessary code to connect to your database<br>const mongoose = require(&#39;mongoose&#39;);<br><br>function connect() {<br>  mongoose<br>    .connect(&#39;mongodb://localhost:27017/mydatabase&#39;, {<br>      useNewUrlParser: true,<br>      useUnifiedTopology: true,<br>    })<br>    .then(() =&gt; {<br>      console.log(&#39;Connected to the database&#39;);<br>    })<br>    .catch(error =&gt; {<br>      console.error(&#39;Error connecting to the database:&#39;, error);<br>    });<br>}<br><br>module.exports = { connect };</pre><p><strong>Note:</strong> Replace the MongoDB connection URL (mongodb://localhost:27017/mydatabase) with your own database connection string.</p><h4>Step 3: Setting Up the Frontend (React)</h4><ol><li>Create a new directory for your front-end project.</li><li>Open a terminal or command prompt and navigate to the frontend directory.</li><li>Initialize a new React project using the command: npx create-react-app app-name.</li></ol><h4>Step 4: Creating a Frontend Component</h4><ol><li>Replace the content of src/App.js in your frontend project with the following code:</li></ol><pre>import React, { useEffect, useState } from &#39;react&#39;;<br><br>function App() {<br>  const [backendMessage, setBackendMessage] = useState(&#39;&#39;);<br><br>  useEffect(() =&gt; {<br>    fetch(&#39;http://localhost:3000&#39;)<br>      .then(response =&gt; response.text())<br>      .then(data =&gt; setBackendMessage(data))<br>      .catch(error =&gt; console.log(error));<br>  }, []);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Full Stack Web Application&lt;/h1&gt;<br>      &lt;p&gt;Message from the backend: {backendMessage}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><h4>Step 5: Running the Application</h4><ol><li>Open two separate terminal windows.</li><li>In the first terminal, navigate to the backend directory and start the backend server by running: node index.js.</li><li>In the second terminal, navigate to the frontend directory and start the React development server by running: npm start.</li><li>Access the application by visiting http://localhost:3000 in your browser.</li></ol><p>Congratulations! You have successfully set up a new runnable full stack web application with a database connection. This guide covered the installation of both the frontend (React) and backend (Node.js and Express) components, along with connecting to a database. By following the provided steps, you should now have a working application running locally.</p><p>Feel free to further customize and enhance your application by adding additional routes, and frontend components, or interacting with the database. Remember to install any necessary dependencies and follow best practices as you continue to develop your full stack web application.</p><p>Happy coding and enjoy building your full-stack web application with a database connection!</p><p>I hope you enjoyed this article. If you did, please clap, follow, and subscribe.</p><p>See you at the next one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=925f0372f801" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing Web Applications: Best Practices and Techniques (Part-I)]]></title>
            <link>https://medium.com/@mihirshahwrites/securing-web-applications-best-practices-and-techniques-part-i-7e151be1a1bd?source=rss-9ced4661f27b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e151be1a1bd</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Mihir Shah]]></dc:creator>
            <pubDate>Fri, 14 Jul 2023 11:33:03 GMT</pubDate>
            <atom:updated>2023-07-17T17:16:27.764Z</atom:updated>
            <content:encoded><![CDATA[<h3>Securing Web Applications: Best Practices and Techniques</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*LdVsC7pWEmxS7FMmUXRdfQ.jpeg" /></figure><p>In today’s digital landscape, web application security is of paramount importance. With cyber threats on the rise, it is crucial for developers to implement robust security measures to protect sensitive data and ensure the integrity of their applications. In this blog post, we will explore best practices and techniques for securing web applications, helping developers build safer and more resilient software.</p><h4>Secure Coding Practices</h4><p>Secure coding practices are essential for full-stack developers to ensure the security and integrity of web applications. By following these practices, developers can minimize the risk of vulnerabilities and protect user data from potential attacks. In this section, we will explore key secure coding practices that should be followed in both front-end and back-end development.</p><ol><li><strong>Input Validation:</strong> Input validation is the process of verifying and sanitizing user input to prevent malicious data from compromising the security of a web application. It is crucial to validate user input on both the client-side (front-end) and server-side (back-end) to ensure data integrity. By implementing proper input validation, developers can protect against various attacks, such as cross-site scripting (XSS) and SQL injection.</li></ol><ul><li><strong>Client-side validation:</strong> Implement validation checks using JavaScript to provide immediate feedback to users and reduce unnecessary server requests. However, remember that client-side validation can be bypassed, so server-side validation is equally important.</li><li><strong>Server-side validation: </strong>Validate user input on the server to ensure that data is in the expected format, length, and other constraints. Apply input sanitization techniques to remove or encode potentially malicious characters.</li></ul><p><strong>Example: </strong>When creating a user registration form, front-end validation can be applied to check if the username and password meet certain requirements, such as minimum length or specific character restrictions. On the server side, validate and sanitize the received input to prevent SQL injection or other malicious activities.</p><p><strong>2. Output Encoding: </strong>Output encoding is the process of encoding user-generated or dynamic content before rendering it in a web application. By properly encoding output, developers can prevent cross-site scripting (XSS) attacks and ensure that user-supplied data is not interpreted as code.</p><ul><li><strong>HTML encoding:</strong> Use appropriate HTML encoding techniques to convert special characters to their HTML entity representation, preventing them from being interpreted as code.</li><li><strong>Context-based encoding:</strong> Apply encoding techniques specific to the output context, such as URL encoding, CSS encoding, or JavaScript encoding, depending on where the content is being rendered.</li></ul><p><strong>Example: </strong>When displaying user-generated content in a comment section, apply HTML encoding to ensure that any HTML tags or special characters are rendered as intended and do not pose a security risk.</p><p><strong>3. Secure Error Handling: </strong>Proper error handling is essential to maintain the security and integrity of a web application while providing a good user experience. It involves handling and presenting errors gracefully without revealing sensitive information that could be exploited by attackers.</p><ul><li><strong>Use generic error messages:</strong> Avoid providing specific error details that could potentially expose sensitive information. Instead, use generic error messages that inform users without revealing internal system details.</li><li><strong>Log errors securely: </strong>Implement secure logging practices to capture necessary information for debugging and auditing purposes. Ensure that sensitive data, such as passwords or personally identifiable information (PII), is not logged.</li></ul><p><strong>Example: </strong>When an unexpected error occurs, display a generic error message like “Oops! Something went wrong. Please try again later” to the user. In the server logs, log the relevant error details while omitting sensitive information.</p><p>By adhering to these secure coding practices, full-stack developers can mitigate the risk of security vulnerabilities and protect web applications from common attacks.</p><h4>Secure Authentication and Authorization</h4><p>Secure authentication and authorization are crucial components of web application security. By implementing strong authentication mechanisms, securely storing passwords, and utilizing additional layers of protection like two-factor authentication (2FA) and role-based access control (RBAC), developers can enhance the security of their applications and protect user accounts from unauthorized access.</p><ol><li><strong>Importance of Strong Authentication Mechanisms: </strong>Authentication is the process of verifying the identity of users and granting them access to the appropriate resources within an application. It is essential to use robust authentication mechanisms to ensure that only authorized users can access sensitive information or perform certain actions.</li></ol><ul><li><strong>Implement strong password policies:</strong> Enforce password complexity requirements, such as minimum length, a combination of uppercase and lowercase letters, numbers, and special characters.</li><li><strong>Secure password storage: </strong>Store passwords securely using salted hashing algorithms like bcrypt or Argon2. Salting adds a random value to each password before hashing, making it more challenging for attackers to crack them.</li></ul><p><strong>2. Two-Factor Authentication (2FA): </strong>Two-factor authentication adds an extra layer of security by requiring users to provide two forms of identification before accessing their accounts. This typically involves something the user knows (password) and something the user possesses (a verification code from a mobile app or SMS).</p><ul><li><strong>Implement 2FA methods: </strong>Offer options like time-based one-time passwords (TOTP) generated by authenticator apps (e.g., Google Authenticator, Authy) or SMS-based verification codes.</li><li><strong>Encourage user adoption:</strong> Educate users about the benefits of 2FA and provide clear instructions on how to set it up.</li></ul><p><strong>3. Role-Based Access Control (RBAC): </strong>RBAC is a technique that restricts system access based on predefined roles assigned to users. It helps enforce the principle of least privilege, ensuring users only have access to the resources necessary for their roles and responsibilities.</p><ul><li><strong>Define roles and permissions:</strong> Identify different user roles within the application (e.g., admin, user, guest) and assign appropriate permissions to each role.</li><li><strong>Implement access control checks:</strong> Validate user permissions before allowing access to sensitive functionalities or data.</li></ul><p>By implementing strong authentication mechanisms, securely storing passwords, and leveraging additional security layers like 2FA and RBAC, developers can enhance the security of their web applications and protect user accounts from unauthorized access. Remember to regularly review and update authentication and authorization mechanisms to adapt to evolving security threats.</p><h4><strong>Secure Communication</strong></h4><p>Protecting the confidentiality and integrity of data transmitted between the web application and the user’s browser is vital. Employing secure communication protocols such as HTTPS (HTTP over SSL/TLS) is crucial to achieve this. Here’s an example:</p><p><strong>Example:</strong> Enabling HTTPS for a Web Application To enable HTTPS, obtain an SSL/TLS certificate from a trusted certificate authority (CA). Install the certificate on your web server and configure it to redirect HTTP requests to HTTPS. Update all internal links and resources to use HTTPS to ensure a secure end-to-end connection.</p><h4>Regular Updates and Patching</h4><p>Web application frameworks, libraries, and dependencies may have vulnerabilities that can be exploited. Regularly updating and patching these components is crucial to maintaining a secure environment. Stay up-to-date with security advisories and vulnerability databases to promptly address any known issues.</p><h4>Security Testing</h4><p>Conducting regular security testing, including vulnerability assessments and penetration testing, is essential to identify and address potential weaknesses. Utilize automated tools and manual techniques to thoroughly test your web application’s security posture.</p><p>Securing web applications requires a proactive and comprehensive approach. By following the best practices and techniques outlined in this blog post, developers and organizations can significantly enhance the security of their web applications and protect sensitive user data. Remember, security is an ongoing process that requires continuous monitoring, updates, and improvements to stay ahead of evolving threats.</p><p>Remember, security is an ongoing process that requires continuous monitoring, updates, and improvements to stay ahead of evolving threats.</p><blockquote><strong><em>Stay vigilant and prioritize security in your web application development journey!</em></strong></blockquote><p>I hope you enjoyed this article. If you did, please clap, follow, and subscribe.</p><p>See you at the next one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e151be1a1bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cipher, Decipher, and Hash using the crypto module in Node.js]]></title>
            <link>https://medium.com/@mihirshahwrites/cipher-decipher-and-hash-using-the-crypto-module-in-node-js-e8ecbd38ad0e?source=rss-9ced4661f27b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8ecbd38ad0e</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Mihir Shah]]></dc:creator>
            <pubDate>Tue, 27 Dec 2022 14:47:46 GMT</pubDate>
            <atom:updated>2022-12-28T11:53:40.028Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OdBwXs2HWwjhKR9iGvia7g.jpeg" /><figcaption>Node Crypto Module</figcaption></figure><p>Whenever we create a server-to-client or client-to-server communication, we should always be curious about how to keep it secure and private. No one wants to compromise the data with any cybercriminal.</p><p>So, the question is, how do we protect confidential information?</p><p>In this article, I’ll introduce one of the most commonly used modules for securing data in Node.js, Crypto.</p><p>To implement Crypto in a Node.js application, you should have:</p><ul><li>Node.js and NPM should be installed in your working environment.</li></ul><h3>What is a crypto module in Node.js?</h3><p>The crypto module provides cryptographic functionality that includes a set of wrappers for OpenSSL’s hash, HMAC, cipher, decipher, sign, and verify functions.</p><h3>How to use crypto classes in Node.js</h3><p>Node provides a crypto module by default. There is no need to configure or install it manually.</p><pre>// Import crypto module into your application<br>const crypto = require(&quot;crypto&quot;);</pre><p>Let’s cover some of the crypto classes which is used widely nowadays.</p><h4>Hash:</h4><blockquote>The hash class is a utility for creating hash digests of data.</blockquote><p>Example: Using the createHash(), createHmac(), update(), and digest() methods:</p><pre>// Import crypto module into your application<br>const crypto = require(&quot;crypto&quot;);<br><br>// Creating hash without key using cryto<br>const hash = crypto<br>  .createHash(&quot;sha256&quot;)<br>  .update(&quot;some data to hash&quot;)<br>  .digest(&quot;hex&quot;);<br><br>console.log(hash);</pre><pre>// Import crypto module into your application<br>const crypto = require(&quot;crypto&quot;);<br><br>// Hash data with key<br>const hmac = crypto<br>  .createHmac(&quot;sha256&quot;, &quot;a secret&quot;)<br>  .update(&quot;some data to hash&quot;)<br>  .digest(&quot;hex&quot;);<br><br>console.log(hmac);</pre><p><strong>createHash(algorithm)</strong></p><p>In this function, the algorithm is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are ‘<strong>sha256</strong>’, ‘<strong>sha512</strong>’, etc.</p><p><strong>createHmac(algorithm, key)</strong></p><p>Creates and returns an <em>hmac</em> object that uses the given algorithm and key. For this function, an algorithm is the same as the createHash function.</p><p><strong>update(data)</strong></p><p>Updates the hash content with the given data.</p><p><strong>digest(type)</strong></p><p>Calculates the digest of all the data passed to be hashed (using the update() method). If encoding is provided a string will be returned; otherwise, a Buffer is returned.</p><p>Widely used digestion formats are <strong>‘base64’, ‘hex’, </strong>and<strong> ‘binary’.</strong></p><h4>Cipher and Decipher:</h4><blockquote>Instances of the <strong>Cipher</strong> class are used to encrypt data.</blockquote><blockquote>Instances of the <strong>Decipher</strong> class are used to decrypt data.</blockquote><blockquote>The <a href="https://nodejs.org/api/crypto.html#cryptocreatecipherivalgorithm-key-iv-options"><em>createCipheriv()</em></a> method is used to create Cipher instances. And the <a href="https://nodejs.org/api/crypto.html#cryptocreatedecipherivalgorithm-key-iv-options"><em>createDecipheriv()</em></a> method is used to create Decipher instances.</blockquote><pre>// Node.js example to implement the Cipher and Decipher crypto classes<br><br>// Import crypto module into your application<br>const crypto = require(&quot;crypto&quot;);<br>// Algorithm to be used for encryption and decryption<br>const algorithm = &quot;aes-256-cbc&quot;;<br>// Key to encrypt/decrypt algorithm<br>const key = crypto.randomBytes(32);<br>// IV value for algorithm<br>const iv = crypto.randomBytes(16);<br><br>// A cipher/encryption function to encrypt data<br>function encrypt(text, iv) {<br>  // Creating Cipheriv method with its parameter<br>  let cipher = crypto.createCipheriv(algorithm, Buffer.from(key), iv);<br>  // Calling update method after creating cipher<br>  let encrypted = cipher.update(text, &quot;utf8&quot;, &quot;base64&quot;);<br>  // Calling final method after updating cipher<br>  encrypted += cipher.final(&quot;base64&quot;);<br>  // Returning iv and encrypted data<br>  return {<br>    iv: iv.toString(&quot;hex&quot;),<br>    encryptedData: encrypted,<br>  };<br>}<br><br>// A Decipher/decryption function to decrypt encrypted-data<br>function decrypt(text) {<br>  let iv = Buffer.from(text.iv, &quot;hex&quot;);<br>  let encryptedText = Buffer.from(text.encryptedData, &quot;base64&quot;);<br>  // Creating Decipheriv method with its parameter<br>  let decipher = crypto.createDecipheriv(<br>    algorithm,<br>    Buffer.from(key, &quot;base64&quot;),<br>    iv<br>  );<br>  // Calling update method after creating decipher<br>  let decrypted = decipher.update(encryptedText);<br>  // Calling final method after updating decipher<br>  decrypted = Buffer.concat([decrypted, decipher.final()]);<br>  // returns data after decryption<br>  return decrypted.toString();<br>}<br><br>// Encryption output<br>var output = encrypt(&quot;some text to encrypt&quot;, iv);<br>console.log(output);<br><br>// Decryption output<br>console.log(decrypt(output));</pre><p><strong>createCipheriv(algorithm, key, iv, options) / createDecipheriv(algorithm, key, iv, options)</strong></p><blockquote><strong>createCipheriv()</strong> method is used to create a Cipher object, with the stated algorithm, key, and initialization vector (iv).</blockquote><blockquote><strong>createDecipheriv() </strong>method<strong> </strong>is used to create a <em>Decipher</em> object, with the stated <em>algorithm</em>, <em>key</em> and <em>initialization vector</em> i.e, (iv).</blockquote><ul><li><strong>algorithm: </strong>It is a string-type value that is dependent on <em>OpenSSL</em>. The examples are <em>aes128</em>, <em>aes192</em>, etc.</li><li><strong>key:</strong> Key is used by the algorithm and iv. The key must be based on algorithm bits. e.g., if an algorithm is 192 bits key should be a length of 24 bytes. Similarly, if an algorithm is 128 and 256 bits then its key length should be 16 and 32 bytes.</li><li><strong>iv: </strong>It is an initialization vector that must be uncertain and very unique. If the cipher doesn’t require <em>iv</em> then it can be <em>null</em>.</li><li><strong>options:</strong> It is an optional parameter that is used to control stream behavior.</li></ul><p><strong>update(data[, inputEncoding][</strong>, <strong>outputEncoding])</strong></p><blockquote>This method is used to update the cipher with data according to the given encoding format.</blockquote><ul><li><strong>data: </strong>It is used to update the cipher with new content.</li><li><strong>inputEncoding: </strong>Input encoding format. If the inputEncoding<strong> </strong>argument is given, the data argument is a string using the specified encoding. If the inputEncoding argument is not given, data must be a <a href="https://nodejs.org/api/buffer.html">Buffer</a>, TypedArray, or DataView. If data is a <a href="https://nodejs.org/api/buffer.html">Buffer</a>, TypedArray, or DataView then inputEncoding is ignored.</li><li><strong>outputEncoding: </strong>Output encoding format. The outputEncoding<strong> </strong>specifies the output format of the enciphered data. If the outputEncoding is specified, a string using the specified encoding is returned. If no outputEncoding is provided, a <a href="https://nodejs.org/api/buffer.html">Buffer</a> is returned.</li></ul><p><strong>final([outputEncoding])</strong></p><blockquote>Once the final() method has been called, the Cipher object can no longer be used to encrypt data.</blockquote><ul><li><strong>outputEncoding:</strong> The encoding of the return value.</li></ul><p>That’s all for this article. For an in-depth look at the cryptographic module, check out the <a href="https://nodejs.org/api/crypto.html">official documentation</a>.</p><p>I hope you enjoyed this article. If you did, please clap, follow, and subscribe.</p><p>See you at the next one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8ecbd38ad0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>