dbublik/cryptography

A lightweight cryptography library for string encryption and decryption

v1.0.1 2025-03-10 21:51 UTC

README

PHP Version Requirement License Tests Lint Code coverage Mutation score

Need to encrypt and decrypt strings effortlessly? Encrypter does it for you with just two simple methods.

Installation

composer require dbublik/cryptography

Usage

Initialize encrypter:

use DBublik\Cryptography\Encrypter;

$secretKey = 'your_secret_key';
$encrypter = Encrypter::create($secretKey);

or prepare it for a container, e.g. for Symfony:

// config/services.php

namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use DBublik\Cryptography\Encrypter;

return function(ContainerConfigurator $container): void {
    $services = $container->services();

    $services->set(Encrypter::class)
        ->factory([null, 'create'])
        ->args([env('YOUR_SECRET_KEY')]);
};

Available encryption algorithms: aes-128-gcm, aes-192-gcm and aes-256-gcm (by default).

Encrypt:

final readonly class ExampleService
{
    public function __construct(
        private \DBublik\Cryptography\Encrypter $encrypter,
    ) {}

    public function save(#[\SensitiveParameter] string $sensitiveValue): void
    {
        $encryptedValue = $this->encrypter->encrypt($sensitiveValue);

        // Don't forget to save $encryptedValue somewhere
    }
}

Decrypt:

final readonly class ExampleService
{
    public function __construct(
        private \DBublik\Cryptography\Encrypter $encrypter,
    ) {}

    public function doSomething(string $encryptedValue): mixed
    {
        $sensitiveValue = $this->encrypter->decrypt($encryptedValue);

        // Be careful! Do not show $sensitiveValue to anyone
    }
}

Supported PHP versions

PHP 8.2 and later.