[PHP] mcrypt (MCRYPT_3DES + MCRYPT_MODE_CFB) <-> openssl (DES-EDE3-CFB8) 상호호환
PHP 2024. 5. 20. 17:18
mcrypt의 MCRYPT_3DES + MCRYPT_MODE_CFB와 호환되는 openssl 사용법.
<?php
// 원본 문자열
$msg = 'hello world';
// 암호화 키
$key = str_pad('my_key', 24, chr(0));
// 알고리즘
$cipher = 'DES-EDE3-CFB8';
// iv
$ivSize = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivSize);
// 암호화 (mcrypt)
$encMcrypt = mcrypt_encrypt(MCRYPT_3DES, $key, $msg, MCRYPT_MODE_CFB, $iv);
// 암호화 (openssl)
$encOpenssl = openssl_encrypt(pkcs5Pad($msg, $ivSize), $cipher, $key, OPENSSL_RAW_DATA, $iv);
// 복호화 (openssl로 암호화된 것을 mcrypt로)
$decOpensslToMcrypt = mcrypt_decrypt(MCRYPT_3DES, $key, $encOpenssl, MCRYPT_MODE_CFB, $iv);
// 복호화 (mcrypt로 암호화된 것을 openssl로)
$decMcryptToOpenssl = openssl_decrypt($encMcrypt, $cipher, $key, OPENSSL_RAW_DATA, $iv);
printf("[ENCRYPT]\nmcrypt: %s\nopenssl: %s\n\n", bin2hex($encMcrypt), bin2hex($encOpenssl));
printf("[DECRYPT]\nencrypt(openssl)->decrypt(mcrypt): %s\nencrypt(mcrypt)->descrypt(openssl): %s\n", $decOpensslToMcrypt, $decMcrypt
ToOpenssl);
/*
출력결과는 아래와 같음
[ENCRYPT]
mcrypt: f6cceaaf3d077cf76362b2
openssl: f6cceaaf3d077cf76362b26a4cdb37ab
[DECRYPT]
encrypt(openssl)->decrypt(mcrypt): hello world
encrypt(mcrypt)->descrypt(openssl): hello world
*/
function pkcs5Pad(string $txt, int $blockSize): string
{
$padLen = $blockSize - (strlen($txt) % $blockSize);
$padLen = $padLen == $blockSize ? 0 : $padLen;
return $txt . str_repeat("\x00", $padLen);
}