JavaScript class that provides methods for storing and retrieving encrypted data of any type using the localStorage
API:
class SecureLocalStorage {
constructor(secretKey) {
this.secretKey = secretKey;
}
encrypt(data) {
const encryptedData = CryptoJS.AES.encrypt(JSON.stringify(data), this.secretKey).toString();
return encryptedData;
}
decrypt(encryptedData) {
const decryptedBytes = CryptoJS.AES.decrypt(encryptedData, this.secretKey);
const decryptedData = JSON.parse(decryptedBytes.toString(CryptoJS.enc.Utf8));
return decryptedData;
}
store(key, data) {
const encryptedData = this.encrypt(data);
localStorage.setItem(key, encryptedData);
}
retrieve(key) {
const encryptedData = localStorage.getItem(key);
if (encryptedData) {
const decryptedData = this.decrypt(encryptedData);
return decryptedData;
}
return null;
}
remove(key) {
localStorage.removeItem(key);
}
}
In this example, we create a class called SecureLocalStorage
that takes a secretKey
as a constructor parameter. This secretKey
is used for encrypting and decrypting the data using the Advanced Encryption Standard (AES) algorithm.
The class provides the following methods:
encrypt(data)
: Encrypts the provided data using AES encryption and thesecretKey
.decrypt(encryptedData)
: Decrypts the provided encrypted data using AES decryption and thesecretKey
.store(key, data)
: Encrypts the data and stores it in thelocalStorage
with the specified key.retrieve(key)
: Retrieves the encrypted data fromlocalStorage
using the key, decrypts it, and returns the original data.remove(key)
: Removes the data associated with the specified key fromlocalStorage
.
Please note that this example requires the CryptoJS library to perform encryption and decryption using AES. Make sure to include the CryptoJS library in your project before using this class.
Here’s an example usage of the SecureLocalStorage
class:
// Create an instance of SecureLocalStorage with a secret key
const secureStorage = new SecureLocalStorage('mySecretKey');
// Store data in localStorage
const data = { username: 'johnDoe', email: 'johndoe@example.com' };
secureStorage.store('userData', data);
// Retrieve and decrypt data from localStorage
const retrievedData = secureStorage.retrieve('userData');
console.log(retrievedData); // { username: 'johnDoe', email: 'johndoe@example.com' }
// Remove data from localStorage
secureStorage.remove('userData');
In this example, we create an instance of SecureLocalStorage
with the secret key 'mySecretKey'
. We then store a sample data
object using the store
method and retrieve it using the retrieve
method, which automatically decrypts the data. Finally, we remove the stored data using the remove
method.
Remember to use a strong and secure secret key to ensure the confidentiality of the encrypted data.