Skip to content

Instantly share code, notes, and snippets.

@pchelk1n
Last active September 21, 2020 12:51
Show Gist options
  • Save pchelk1n/7aa1fbf6a09d3f245aab97646d4c5077 to your computer and use it in GitHub Desktop.
Save pchelk1n/7aa1fbf6a09d3f245aab97646d4c5077 to your computer and use it in GitHub Desktop.
Simple encrypt
<?php
namespace App\Service;
class Encrypter
{
private const METHOD = 'aes-256-cbc';
private const DELIMITER = '::';
private const WRONG_ENCRYPT_SYMBOLS = ['+','/','='];
private const CORRECT_ENCRYPT_SYMBOLS = ['-','_',''];
private const WRONG_DECRYPT_SYMBOLS = ['+','/'];
private const CORRECT_DECRYPT_SYMBOLS = ['-','_'];
/**
* @var string
*/
private $secret;
public function __construct(string $secret)
{
$this->secret = $secret;
}
public function encrypt(string $data): string
{
$length = openssl_cipher_iv_length(self::METHOD);
$iv = random_bytes($length);
$encrypted = openssl_encrypt($data, self::METHOD, $this->secret, 0, $iv);
$stringToEncode = $encrypted.self::DELIMITER.$iv;
return str_replace(self::WRONG_ENCRYPT_SYMBOLS, self::CORRECT_ENCRYPT_SYMBOLS, base64_encode($stringToEncode));
}
public function decrypt(string $data): string
{
$normalizeData = str_replace(self::CORRECT_DECRYPT_SYMBOLS, self::WRONG_DECRYPT_SYMBOLS, $data);
[$encrypted, $iv] = explode(self::DELIMITER, base64_decode($normalizeData), 2);
return openssl_decrypt($encrypted, self::METHOD, $this->secret, 0, $iv);
}
}
@pchelk1n
Copy link
Author

pchelk1n commented Sep 11, 2017

For Symfony

AppBundle\Service\Encrypter:
        arguments: ["%secret%"]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment