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 Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
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
Partner Zones AWS Cloud
by AWS Developer Relations
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
Partner Zones
AWS Cloud
by AWS Developer Relations
  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.

Erkin Karanlık user avatar by
Erkin Karanlık
·
Nov. 08, 22 · Code Snippet
Like (1)
Save
Tweet
Share
3.59K 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.

Popular on DZone

  • How Elasticsearch Works
  • Choosing the Right Framework for Your Project
  • Introduction to Container Orchestration
  • Building Microservice in Golang

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: