feat: add encryption and date service utilities
- Implemented EncryptionService for secure data handling with AES encryption. - Created DateService for advanced date manipulation and formatting. - Developed EncryptionDemo and DateServiceComponent for interactive demonstrations. - Added LocalStorage demo for encrypted data storage and retrieval. - Established ESLint and TypeScript configurations for utils package. - Included example utility function for demonstration purposes.
This commit is contained in:
@@ -0,0 +1 @@
|
||||
export const ENC_STORAGE_KEY = 'zkwqyo3RpNEh8un2CIAs'; //TODO change value from environment
|
||||
@@ -0,0 +1,70 @@
|
||||
import { AES, enc } from 'crypto-js';
|
||||
import { ENC_STORAGE_KEY } from './encryption-key';
|
||||
|
||||
/**
|
||||
* Interface contract supaya method konsisten
|
||||
*/
|
||||
interface IEncryptionService {
|
||||
encrypt(data: string): string;
|
||||
decrypt(encryptedData: string): string;
|
||||
}
|
||||
|
||||
export class EncryptionService implements IEncryptionService {
|
||||
private readonly _key: string;
|
||||
|
||||
/**
|
||||
* @param key (Optional) Jika tidak diisi, otomatis pakai ENC_STORAGE_KEY
|
||||
*/
|
||||
constructor(key: string = ENC_STORAGE_KEY) {
|
||||
if (!key) {
|
||||
throw new Error('[EncryptionService] Encryption key is missing/empty.');
|
||||
}
|
||||
this._key = key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mengenkripsi string plain text.
|
||||
*/
|
||||
public encrypt(data: string): string {
|
||||
if (!data) {
|
||||
return '';
|
||||
}
|
||||
return AES.encrypt(data, this._key).toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Mendekripsi string terenkripsi.
|
||||
* Mengembalikan string kosong '' jika gagal decrypt atau format salah.
|
||||
*/
|
||||
public decrypt(encryptedData: string): string {
|
||||
if (!encryptedData) {
|
||||
return '';
|
||||
}
|
||||
|
||||
try {
|
||||
const bytes = AES.decrypt(encryptedData, this._key);
|
||||
const originalText = bytes.toString(enc.Utf8);
|
||||
|
||||
// Validasi tambahan: jika hasil decrypt kosong, berarti key salah atau data corrupt
|
||||
if (!originalText) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return originalText;
|
||||
} catch (error) {
|
||||
console.error('[EncryptionService] Decryption failed:', error);
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
// --- Static Helper (Singleton Pattern sederhana) ---
|
||||
// Supaya tidak perlu 'new EncryptionService()' berulang kali
|
||||
private static instance: EncryptionService;
|
||||
|
||||
public static getInstance(): EncryptionService {
|
||||
if (!EncryptionService.instance) {
|
||||
EncryptionService.instance = new EncryptionService();
|
||||
}
|
||||
return EncryptionService.instance;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user