Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sample of programmatic AES256GCM and blowfish encryption and decryption of secret value in Sugar
<?php
// Enrico Simonetti
// enricosimonetti.com
//
// 2019-05-13
// Sample of programmatic AES256GCM and blowfish encryption and decryption of secret value in Sugar
// secret value to encrypt for storage purposes, and to decrypt real-time
$value = 'my secret value goes here'; // sample string to encrypt
// base 64 encoding the value to make sure it does not contain unwanted characters
$encodedValue = base64_encode($value);
// Method 1 - AES256GCM available on newer Sugar versions
use Sugarcrm\Sugarcrm\Security\Crypto\AES256GCM;
// encryption key based on unique identifier
$encryptionKey = 'my_encryption_key_identifier'; // change this string based on needs
// new encryption object with the predefined key
$aes = new AES256GCM($encryptionKey);
// encryption via AES256GCM with the custom encryption/decryption key
$encryptedValue = $aes->encrypt($encodedValue);
// printing encrypted value
//echo 'Encrypted value: ' . $encryptedValue . PHP_EOL;
// printing base 64 encoded, encrypted value for ease of storage
$storedValue = base64_encode($encryptedValue);
echo 'Base 64 encoded encrypted value (for ease of storage): ' . $storedValue . PHP_EOL;
// decoding via blowfish with the custom encryption/decryption key, of the base 64 decoded stored value
$clearTextValue = base64_decode($aes->decrypt(base64_decode($storedValue)));
// printing decripted value for test purposes only
echo 'Decrypted value: ' . $clearTextValue . PHP_EOL;
// ---------------------------------------------
// Method 2 - blowfish
use Sugarcrm\Sugarcrm\Security\Crypto\Blowfish;
// encryption key based on unique identifier
$encryptionKey = Blowfish::getKey('my_encryption_key_identifier'); // change this string based on needs
// encryption via blowfish with the custom encryption/decryption key
$encryptedValue = Blowfish::encode($encryptionKey, $encodedValue);
// printing encrypted value
//echo 'Encrypted value: ' . $encryptedValue . PHP_EOL;
// printing base 64 encoded, encrypted value for ease of storage
$storedValue = base64_encode($encryptedValue);
echo 'Base 64 encoded encrypted value (for ease of storage): ' . $storedValue . PHP_EOL;
// decoding via blowfish with the custom encryption/decryption key, of the base 64 decoded stored value
$clearTextValue = base64_decode(Blowfish::decode($encryptionKey, base64_decode($storedValue)));
// printing decripted value for test purposes only
echo 'Decrypted value: ' . $clearTextValue . PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.