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.
Join the DZone community and get the full member experience.
Join For FreeEncrypting 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={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
}
}
Opinions expressed by DZone contributors are their own.
Comments