Skip to content

Instantly share code, notes, and snippets.

@knoonrx
Last active January 7, 2022 18:32
Show Gist options
  • Save knoonrx/db63858d0b1d718a453b57e23a068790 to your computer and use it in GitHub Desktop.
Save knoonrx/db63858d0b1d718a453b57e23a068790 to your computer and use it in GitHub Desktop.
CryptoJS.AES.encrypt to PHP - PHP implementation to Encrypt and decrypt a string compatible with crypto-js library AES default settings
class CryptoJSAES
{
public function encrypt($passphrase, $data, $salt = null): string
{
$salt = $salt ?: openssl_random_pseudo_bytes(8);
[$key, $iv] = $this->_evpKDF($passphrase, $salt);
$ct = openssl_encrypt($data, 'aes-256-cbc', $key, true, $iv);
return $this->_encode($ct, $salt);
}
public function decrypt($passphrase, $base64): bool|string
{
[$ct, $salt] = $this->_decode($base64);
[$key, $iv] = $this->_evpKDF($passphrase, $salt);
return openssl_decrypt($ct, 'aes-256-cbc', $key, true, $iv);
}
private function _evpKDF($passphrase, $salt): array
{
$salted = '';
$dx = '';
while (strlen($salted) < 48) {
$dx = md5($dx . $passphrase . $salt, true);
$salted .= $dx;
}
$key = substr($salted, 0, 32);
$iv = substr($salted, 32, 16);
return [$key, $iv];
}
private function _decode($base64): array|string
{
$data = base64_decode($base64);
if (!str_starts_with($data, 'Salted__')) {
return '';
}
$salt = substr($data, 8, 8);
$ct = substr($data, 16);
return [$ct, $salt];
}
private function _encode($ct, $salt): string
{
return base64_encode('Salted__' . $salt . $ct);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment