Skip to content

Instantly share code, notes, and snippets.

@toshimaru
Last active September 3, 2024 08:07
Show Gist options
  • Save toshimaru/255dd68850efdf2f7363667e1207d856 to your computer and use it in GitHub Desktop.
Save toshimaru/255dd68850efdf2f7363667e1207d856 to your computer and use it in GitHub Desktop.
Convert PHP `mcrypt_encrypt` fucntion to `openssl_encrypt` function. Blog: https://blog.toshima.ru/2024/07/28/mcrypt-encrypt-to-openssl-encrypt.html

Launch php:7.2 image

$ docker run -it php:7.2 bash

Install mcrypt

# apt update && apt install -y libmcrypt-dev
# pecl install mcrypt
# docker-php-ext-enable mcrypt
# cat /usr/local/etc/php/conf.d/docker-php-ext-mcrypt.ini
extension=mcrypt
<?php
$key = "my-crypt-key-123";
$data = "my-data";
$iv = 'initial-vector-1';
/// mcrypt ///
$encrypted_data = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv);
$encrypted_data = base64_encode($encrypted_data);
echo $encrypted_data; // 36PTiQsQwsw3M2R6KEcKOA==
/// openssl ///
function pad_zero($data) {
$block_size = 16;
$padding = $block_size - (strlen($data) % $block_size);
return $data . str_repeat("\0", $padding);
}
$method = "aes-128-cbc";
$encrypted_data = openssl_encrypt(pad_zero($data), $method, $key, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING , $iv);
$encrypted_data = base64_encode($encrypted_data);
echo $encrypted_data; // 36PTiQsQwsw3M2R6KEcKOA==
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment