Inicializar el proyecto
npm init vite@latest dummy -- --template react
cd dummy
npm install
Instalar crypto-js
npm i crypto-js
Creación de función encriptar
const encryptStorage = (name, data) => {
const encrypt = CryptoJS.AES.encrypt(
JSON.stringify(data),
secretKey,
).toString()
localStorage.setItem(name, encrypt)
}
Creación función desencriptar
const decryptStorage = (name) => {
const encrypt = localStorage.getItem(name)
const decrypt = CryptoJS.AES.decrypt(encrypt, secretKey).toString(
CryptoJS.enc.Utf8,
)
setRes(JSON.parse(decrypt))
}
Código final
import CryptoJS from 'crypto-js'
import { useState } from 'react'
function App() {
const secretKey = 'tu secret key'
const data = { nombre: 'gabriel' }
const [res, setRes] = useState([])
const encryptStorage = (name, data) => {
const encrypt = CryptoJS.AES.encrypt(
JSON.stringify(data),
secretKey,
).toString()
localStorage.setItem(name, encrypt)
}
const decryptStorage = (name) => {
const encrypt = localStorage.getItem(name)
const decrypt = CryptoJS.AES.decrypt(encrypt, secretKey).toString(
CryptoJS.enc.Utf8,
)
setRes(JSON.parse(decrypt))
}
return (
<div className="App">
<div className="btn" onClick={() => encryptStorage('dummy', data)}>
encriptar
</div>
<div className="btn" onClick={() => decryptStorage('dummy')}>
desencriptar
</div>
{JSON.stringify(res)}
</div>
)
}
export default App;