1.0.7 • Published 6 months ago
ifo-secure-local-storage-js v1.0.7
secure-local-storage-js
A secure wrapper for localStorage with AES encryption support using CryptoJS. This package provides an easy-to-use solution for encrypting and storing sensitive data in the browser's local storage.
Features
- 🔒 AES Encryption: Securely encrypt and decrypt local storage items
- 🔑 Configurable Encryption Key
- 🌐 Browser Compatibility
- 📦 TypeScript Support
- 🛡️ Error Handling
- 🔧 Environment Variable Support
Installation
Install the package using npm:
npm install secure-local-storage-js
Usage
Basic Usage
import SecureLocalStorage from 'ifo-secure-local-storage-js';
// Initialize with default key
const secureStorage = new SecureLocalStorage();
// Store data
secureStorage.setItem('user', {
name: 'John Doe',
email: 'john@example.com'
});
// Retrieve data
const user = secureStorage.getItem('user');
console.log(user);
// Output: { name: 'John Doe', email: 'john@example.com' }
// Remove data
secureStorage.removeItem('user');
Custom Encryption Key
// Initialize with a custom encryption key
const secureStorage = new SecureLocalStorage('my-custom-secret-key');
Using Environment Variables
You can also set the encryption key using an environment variable:
// In your .env file or environment configuration
SECURE_APP_HASH_KEY=your-secret-key
API
new SecureLocalStorage(key?: string)
Creates a new instance of SecureLocalStorage
key
(optional): Custom encryption key. If not provided, it uses theSECURE_APP_HASH_KEY
environment variable or a default key.
Methods
setItem(key: string, value: any): void
Encrypts and stores an item in local storage
getItem(key: string): any
Retrieves and decrypts an item from local storage
removeItem(key: string): void
Removes an item from local storage
encrypt(value: any): string | null
Manually encrypt a value
decrypt(value: string): any
Manually decrypt a value
Security Notes
- Always use a strong, unique encryption key
- Do not store the encryption key in client-side code
- This is suitable for client-side data protection, not for highly sensitive information
Error Handling
The library provides basic error handling:
- Failed encryptions/decryptions return
null
- Error messages are logged to the console
Compatibility
- Requires a modern browser with
localStorage
support - Works with server-side rendering (with appropriate polyfills)
Dependencies
crypto-js
: For AES encryption
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.