FastSitePHP\Security\Crypto

FastSitePHP Crypto Class

This is a helper class using a Facade Software Design Pattern to simplify Secure Encryption, Data Signing, and JWT usage.

This class allows for only the default secure settings of each object and requires secure keys to be defined in either the App Config Array or as Environment Variables.

By default Signed Data and JSON Web Tokens are valid for 1 hour and expire after. The expiration time can be changed from a parameter when calling either [sign()] or [encodeJWT].

Example usage:
    $app->config['ENCRYPTION_KEY'] = 'dd8daccb9e2b66321a......';
    $encrypted_text = Crypto::encrypt($data);
    $decrypted_data = Crypto::decrypt($encrypted_text);

[$app] Config (or Environment Variables) Settings:
    ENCRYPTION_KEY
        encrypt()
        decrypt()
        encryptFile()
        decryptFile()
    SIGNING_KEY
        sign()
        verify()
    JWT_KEY
        encodeJWT()
        decodeJWT()

Source Code

GitHub

رمز المثال

Security - Encrypt and Decrypt Data

// Generate a Key for Encryption.
// The key is a long hex string of secure random bytes.
// The key would typically be saved with your app or in config.
$crypto = new \FastSitePHP\Security\Crypto\Encryption();
$key = $crypto->generateKey();

// Encrypt and Decrypt using the Crypto Helper Class with Config Settings.
// Data of different data types can be encrypted and returned in the
// same format (string, int, object, etc).
$app->config['ENCRYPTION_KEY'] = $key;
$encrypted_text = \FastSitePHP\Security\Crypto::encrypt($data);
$decrypted_data = \FastSitePHP\Security\Crypto::decrypt($encrypted_text);

// Encrypt and Decrypt using the Encryption Class. This class
// provides many additional options that are not in the helper class.
$encrypted_text = $crypto->encrypt($data, $key);
$decrypted_data = $crypto->decrypt($encrypted_text, $key);

Security - Encrypt and Decrypt a File

// FastSitePHP allows for fast authenticated encryption of any size file
// (even large files that are many gigs in size). The code used for encryption
// is compatible with shell commands and a Bash Script [encrypt.sh] that works
// on Linux and Unix Computers. The Bash Script can be downloaded from this site,
// and will work on most Linux OS's without having to install anything.

// Generate a Key for Encryption
$crypto = new \FastSitePHP\Security\Crypto\FileEncryption();
$key = $crypto->generateKey();

// Build file paths of files to save based on the original name
$enc_file = $file_path . '.enc';
$output_file = $enc_file . '.decrypted';

// Encrypt and Decrypt using the Crypto Helper Class with Config Settings.
// A [FileEncryption] class also exists with additional options.
$app->config['ENCRYPTION_KEY'] = $key;
\FastSitePHP\Security\Crypto::encryptFile($file_path, $enc_file);
\FastSitePHP\Security\Crypto::decryptFile($enc_file, $output_file);

Security - Encode and Decode a JSON Web Token (JWT)

// The JWT Payload can be either an Object or an Array (Dictionary).
$payload = [
    'User' => 'John Doe',
    'Roles' => ['Admin', 'SQL Editor']
];

// Generate a Key for Encoding (Signing).
// The key is a long hex string of secure random bytes.
// The key would typically be saved with your app or in config.
$jwt = new \FastSitePHP\Security\Crypto\JWT();
$key = $jwt->generateKey();

// Encode and Decode JWT with the Crypto Helper Class with Config Settings.
// When using the default parameters with the helper class the data has a
// 1-hour timeout.
$app->config['JWT_KEY'] = $key;
$token = \FastSitePHP\Security\Crypto::encodeJWT($payload);
$data  = \FastSitePHP\Security\Crypto::decodeJWT($token);

// Encode (Sign) and Decode (Verify) using the JWT Class. When using
// default settings with the JWT Class, no timeout is specified, all
// claims are validated, and a secure key is required.
$token = $jwt->encode($payload, $key);
$data  = $jwt->decode($token, $key);

// Add Claims to the Payload and use an Insecure Key for Compatibility
// with other sites (Often online demos of JWT are shown using simple
// passwords for the key). By default keys are required to be secure
// with proper length and in either Base64 or Hex format.

$payload = $jwt->addClaim($payload, 'exp', '+10 minutes');
$payload = $jwt->addClaim($payload, 'iss', 'example.com');

$jwt
    ->useInsecureKey(true)
    ->allowedIssuers(['example.com']);

$insecure_key = 'password123';
$token = $jwt->encode($payload, $insecure_key);
$data  = $jwt->decode($token, $insecure_key);

Security - Sign and Verify Data

// Using the [SignedData] is similar in concept to using JWT.
// A client can read the data but not modify it.

// Generate a Key for Signing.
// The key is a long hex string of secure random bytes.
// The key would typically be saved with your app or in config.
$csd = new \FastSitePHP\Security\Crypto\SignedData();
$key = $csd->generateKey();

// Sign and Verify using the Crypto Helper Class with Config Settings.
// When using the default parameters with the helper class the data has
// a 1-hour timeout. Data of different data types can be signed and
// verified to the original format (string, int, object, etc).
$app->config['SIGNING_KEY'] = $key;
$signed_text   = \FastSitePHP\Security\Crypto::sign($data);
$verified_data = \FastSitePHP\Security\Crypto::verify($signed_text);

// Sign and Verify using the SignedData Class. The SignedData Class
// allows for additional options and doesn't use config settings.
// The parameter [$expire_time] is optional.
$expire_time   = '+20 minutes';
$signed_text   = $csd->sign($data, $key, $expire_time);
$verified_data = $csd->verify($signed_text, $key);

Methods

encrypt($data)

Static Function

Encrypt data (string, int, float, bool, object, or array) and return the encrypted text as a base64-url string.

Returns: string

decrypt($encrypted_text)

Static Function

Decrypt data that was encrypted using the [encrypt()] function and return the original value.

The same data type is returned so if a string was encrypted a string will be returned and if an array was encrypted then an array will be returned. Objects of type stdClass or custom classes that were encrypted are returned as an Array (Dictionary).

If decryption fails then null will be returned.

Returns: mixed

sign($data, $expire_time = '+1 hour')

Static Function

Sign data (string, int, float, bool, object, or array) and return the signed data in one of the following formats:
    'base64url(data).type.base64url(signature)'
    'base64url(data).type.timestamp.base64url(signature)'

The default expiration time is 1 hour; this can be changed to a different time or turned off passing [null].

Returns: string

verify($signed_text)

Static Function

Verify data that was signed using the [sign()] function and return the original value.

The same data type is returned so if a string was signed a string will be returned and if an array was signed then an array will be returned. Objects of type stdClass or custom classes that were signed are returned as an Array (Dictionary).

If verification fails then null will be returned.

Returns: mixed

encryptFile($file_path, $enc_file)

Static Function

Encrypt a file

If a file is 10 MB or smaller (or any size on Windows) then it will be processed in memory, otherwise the file will be processed using shell commands. This allows for files of any size to be encrypted.

If you need to encrypt files that are larger than 2 GB on a 32-Bit OS then you should use the [FileEncryption] class directly like this:
    $crypto = new FileEncryption();
    $crypto->processFilesWithCmdLine(true);
    $crypto->encryptFile($file_path, $enc_file, $key);

decryptFile($enc_file, $output_file)

Static Function

Decrypt a file that was created from [encryptFile()]. The same memory and OS rules apply for file processing.

This function has no return value so if decryption fails an exception is thrown.

encodeJWT($payload, $exp_time = '+1 hour')

Static Function

Create a JSON Web Token (JWT) with a default expiration time of 1 hour.

Returns: string

decodeJWT($token)

Static Function

Decode and Verify a JWT. If the token is not valid null will be returned.

Returns: array | null - The payload that was originally encoded.