Last active
September 21, 2020 12:51
-
-
Save pchelk1n/7aa1fbf6a09d3f245aab97646d4c5077 to your computer and use it in GitHub Desktop.
Simple encrypt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For Symfony