DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Moving From Full-Stack Developer To Web3 Pioneer
  • Having Fun with the Lightning Design System for React
  • Production-Grade React Project Structure: From Setup to Scale
  • React Server Components in Next.js 15: A Deep Dive

Trending

  • How to Build Your Own AI SRE From Scratch
  • Why Your GPU Fleet Is Both Full and Idle: Building a Capacity Orchestration Layer
  • Supercharging AI Agents with Azure Context: A Hands-On Guide to Azure MCP
  • PWA on iOS, Part 1: PWAs on the iPhone Are Older Than They Look

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Data Engineering
  3. Data
  4. Data Encrypt — Decrypt in React Application

Data Encrypt — Decrypt in React Application

The information we entered in this article contains the steps of how we can encrypt and decrypt in the react application.

By 
Erkin Karanlık
·
Nov. 08, 22 · Code Snippet
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
21.8K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Encrypting the information entered in the login step of our Front End Projects is important for the security step.

The information we entered in this article contains the steps of how we can encrypt and decrypt in the react application.

For example, in the React application, the first username and password information should be correct on the login screen below. We can do this through a login service that we can verify. 

After encrypting and decrypting the entered log data, it shows the possible views on chrome as encrypted.

In order to use the encrypt and decrypt features in our React application, the first step we need to do is to install the crypto.js library.

You can use the following path for the installation address.

npm install crypto-js 

npm i @types/crypto-js

We need to import this library in the newly created Utilty.tsx file.

 
import * as CryptoJS from 'crypto-js'


A constant named REACT_APP_SECRET_KEY has been specified that the Encrypt and Decrypt functions can use.

Encrypt function: As input, we can receive a string dataset in JSON format. We send the plainText we receive as input to the encrypt function with the secretKey value (REACT_APP_SECRET_KEY) and return an encrypted cipherText variable.

Decrypt function: We take the cipherText variable produced in the previous step as input and assign it to a variable named bytes with the secretKey value (REACT_APP_SECRET_KEY). Then we return plainText in UTF8 format.


 
const secretKey = process.env.REACT_APP_SECRET_KEY ? process.env.REACT_APP_SECRET_KEY : '12345'
export const encrypt = ( plainText: string ) => {
    const cipherText = CryptoJS.AES.encrypt(plainText, secretKey).toString()
    return cipherText
}

export const decrypt = ( cipherText:string ) => {
    const bytes = CryptoJS.AES.decrypt(cipherText, secretKey )
    const plainText = bytes.toString(CryptoJS.enc.Utf8)
    return plainText


Below, "sendForm" is triggered in the Form onSubmit method after login.

 Form onSubmit method after login.

 
 <form onSubmit={sendForm}>
                    <div className='mb-3'>
                        <input onChange={(evt) => setEmail(evt.target.value)} required type='email' className='form-control' placeholder='E-Mail'></input>
                    </div>
                    <div className='mb-3'>
                        <input onChange={(evt) => setPassword(evt.target.value)} required type='password' className='form-control' placeholder='Password'></input>
                    </div>
                    <div className='mb-3 form-check'>
                        <input onChange={(evt) => setRemember(!remember) } type='checkbox' className='form-check-input' id='remember'></input>
                        <label className='form-check-label' htmlFor='remember'>Remember</label>
                    </div>
                    <button type='submit' className='btn btn-success'>Login</button>
                </form>


The userLogin service is called with the event information from the Send Form. If the login information is successful, the user information is converted to JSON format with the JSON.stringify feature. Information in JSON format is given as input to the encrypt method. Thus, the data is encrypted.

 
 const sendForm = ( evt: React.FormEvent ) => {
    evt.preventDefault()
    setAlertMessage('')
    userLogin(email, password).then( res => {
        const user = res.data.user[0]
        const bilgi = user.bilgiler
        if ( user.durum && bilgi ) {
            const stBilgiler = JSON.stringify(bilgi)
            const encryptBilgiler = encrypt(stBilgiler)
            sessionStorage.setItem('user', encryptBilgiler)
            if (remember) {
                localStorage.setItem('user', encryptBilgiler)
            }
            navigate('/dashboard')
        }else {
            setAlertMessage( user.mesaj )
        }
    }).catch( error => {
        console.log( error.message );
    }).finally(() => {
        console.log("Service Call Finish");
    })
    console.log("this line call");
    
  } 


appRouter.tsx

 
           <Routes>
                <Route path='' element={ userLoginControl() === null ? <Login /> : <Navigate to='/dashboard' /> }></Route>
                <Route path='/dashboard' element={ <Security component={<Dashboard />} /> }></Route>
                <Route path='/users' element={ <Security component={<Users />} /> } ></Route>
            </Routes>


The information encrypted with the userLoginControl method in the route is decrypted again, and login is provided.

 
export const userLoginControl = () => {
    const localString = localStorage.getItem('user')
    if ( localString ) {
        sessionStorage.setItem('user', localString)
    }
    const stBilgiler = sessionStorage.getItem('user')
    if ( stBilgiler ) {
        try {
            const decryptBilgiler = decrypt(stBilgiler)
            const bilgiler = JSON.parse(decryptBilgiler) as Bilgiler
            return bilgiler
        } catch (error) {
            sessionStorage.removeItem('user')
            return null
        }
        
    }else {
        return null
    }
}


application Data (computing) React (JavaScript library)

Opinions expressed by DZone contributors are their own.

Related

  • Moving From Full-Stack Developer To Web3 Pioneer
  • Having Fun with the Lightning Design System for React
  • Production-Grade React Project Structure: From Setup to Scale
  • React Server Components in Next.js 15: A Deep Dive

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook