43 lines
976 B
PHP
43 lines
976 B
PHP
<?php
|
|
|
|
namespace App\Libraries;
|
|
|
|
use Throwable;
|
|
|
|
class Encrypter
|
|
{
|
|
private const PREFIX = 'enc::';
|
|
|
|
public function encrypt(string $plainText): string
|
|
{
|
|
if ($plainText === '' || str_starts_with($plainText, self::PREFIX)) {
|
|
return $plainText;
|
|
}
|
|
|
|
$encrypted = service('encrypter')->encrypt($plainText);
|
|
return self::PREFIX . base64_encode($encrypted);
|
|
}
|
|
|
|
public function decrypt(string $cipherText): string
|
|
{
|
|
if ($cipherText === '') {
|
|
return $cipherText;
|
|
}
|
|
|
|
if (! str_starts_with($cipherText, self::PREFIX)) {
|
|
return $cipherText;
|
|
}
|
|
|
|
try {
|
|
$payload = base64_decode(substr($cipherText, strlen(self::PREFIX)), true);
|
|
if ($payload === false) {
|
|
return '';
|
|
}
|
|
|
|
return (string) service('encrypter')->decrypt($payload);
|
|
} catch (Throwable) {
|
|
return '';
|
|
}
|
|
}
|
|
}
|