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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Moving From Full-Stack Developer To Web3 Pioneer
  • Having Fun with the Lightning Design System for React
  • The Ultimate Guide to React Dashboards Part 1: Overview and Analytics
  • The Cypress Edge: Next-Level Testing Strategies for React Developers

Trending

  • Accelerating AI Inference With TensorRT
  • Zero Trust for AWS NLBs: Why It Matters and How to Do It
  • Performance Optimization Techniques for Snowflake on AWS
  • AI’s Role in Everyday Development
  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
18.3K 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
  • The Ultimate Guide to React Dashboards Part 1: Overview and Analytics
  • The Cypress Edge: Next-Level Testing Strategies for React Developers

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!