public without sharing class VIP_EncryptTermsConditionDate {
public static void getKeyAndIV() {
// Generate a 32-byte (256-bit) secret key for AES256-GCM
Blob key = Crypto.generateAesKey(256);
String keyString = EncodingUtil.base64Encode(key); // Securely store this!
updateCustomSetting(keyString);
}
public static void encryptTodayDate() {
// Get today's date
Date todayDate = Date.today();
// Manually construct the date in YYYY-MM-DD format
String formattedDate =
todayDate.year() +
'-' +
(todayDate.month() < 10 ? '0' + todayDate.month() : String.valueOf(todayDate.month())) +
'-' +
(todayDate.day() < 10 ? '0' + todayDate.day() : String.valueOf(todayDate.day()));
Blob dataBlob = Blob.valueOf(formattedDate);
//Get the KEY and IV from custom setting
VIP_Encode_URL__c encodeRec = VIP_Encode_URL__c.getInstance('URLkey');
String keyString = encodeRec.VIP_key__c;
Blob key = EncodingUtil.base64Decode(keyString);
// Additional Authenticated Data for extra security (context binding)
Blob aad = Blob.valueOf('VIP_TERMS_CONDITIONS_DATE');
// Encrypt using AES256-GCM with managed IV (provides authentication + encryption)
Blob encryptedBlob = Crypto.encryptWithManagedIV('AES256-GCM', key, dataBlob,aad);
// Convert encrypted data, IV, and key to Base64 for storage
String encryptedString = EncodingUtil.base64Encode(encryptedBlob)
.replace('+', '-')
.replace('/', '_')
.replace('=', '');;
// Replace '/' with '_' only if '/' exists in the string
// String aemSafeEncryptedString = encryptedString.contains('/') ? encryptedString.replace('/', '_') : encryptedString;
//Requires SYSTEM_MODE because class is without sharing
String encodedURL =
[SELECT VIP_URL__c FROM VIP_URL__mdt WHERE DeveloperName = :VIP_Constants.TERMS_AND_CONDITIONS_URL WITH SYSTEM_MODE].VIP_URL__c +
aemSafeEncryptedString;
System.debug('encodedURL ==>'+encodedURL);
}
private static void updateCustomSetting(String keyString) {
VIP_Encode_URL__c encodeRec = VIP_Encode_URL__c.getInstance('URLkey');
if (encodeRec == null) {
// Create a new record if it doesn't exist
encodeRec = new VIP_Encode_URL__c();
encodeRec.Name = 'URLkey';
}
encodeRec.VIP_key__c = keyString;
VIP_UtilityController.upsertSObjectOperation(new List<VIP_Encode_URL__c>{ encodeRec }, 'VIP_EncryptTermsConditionDate');
}
}