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
Over 2 million developers have joined DZone.
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

  • Stop Writing Dialect-Specific SQL: A Unified Query Builder for Node.js
  • 11 Agentic Testing Tools to Know in 2026
  • Evaluating SOC Effectiveness Using Detection Coverage and Response Metrics
  • Genkit Middleware: Intercept, Extend, and Harden your Gen AI Pipelines
  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 user avatar
Erkin Karanlık
·
Nov. 08, 22 · Code Snippet
Likes (1)
Comment
Save
Tweet
Share
20.5K Views

Join the DZone community and get the full member experience.

Join For Free

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

The likes didn't load as expected. Please refresh the page and try again.

  • 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