PHP7.1环境下用openssl_encrypt替代mcrypt改写3DES加密函数
转换3DES加密函数到OpenSSL(替代废弃的mcrypt)
Hey there, let's get that old mcrypt-based 3DES function updated to use openssl_encrypt—since mcrypt has been deprecated since PHP 7.1, this is the proper modern approach. First, let's break down what your original function does, then map each part to OpenSSL equivalents.
Original Function Breakdown
Your code does these key things:
- Uses 3DES (Triple DES) in CBC mode
- Pads the key to exactly 24 bytes (repeating the start of the key if it's too short)
- Applies PKCS#7 padding to the plaintext (filling with bytes equal to the number of padding bytes needed)
- Returns raw encrypted bytes (your variable name
$encrypt64suggests you might have base64-encoded it later)
Updated OpenSSL-Based Function
Here's the drop-in replacement that matches your original logic 1:1:
function encryptNET3DES($key, $vector, $text) { // OpenSSL identifier for 3DES in CBC mode (matches MCRYPT_3DES + MCRYPT_MODE_CBC) $cipher = 'des-ede3-cbc'; // Match original key handling: pad to 24 bytes, truncate if too long $keyLength = strlen($key); if ($keyLength < 24) { $key .= substr($key, 0, 24 - $keyLength); } elseif ($keyLength > 24) { $key = substr($key, 0, 24); } // 3DES CBC requires an IV exactly 8 bytes long (matching the block size) if (strlen($vector) !== 8) { throw new InvalidArgumentException("IV must be exactly 8 bytes long for 3DES CBC."); } // Encrypt: OPENSSL_RAW_DATA returns raw bytes (like mcrypt_generic) // OpenSSL uses PKCS#7 padding by default, which matches your manual padding logic $encrypted = openssl_encrypt( $text, $cipher, $key, OPENSSL_RAW_DATA, $vector ); // Uncomment this line if your original function returned base64-encoded data // return base64_encode($encrypted); return $encrypted; }
Key Notes About the Conversion
- Cipher Choice:
des-ede3-cbcis the standard OpenSSL name for 3DES in CBC mode—this directly maps to your original mcrypt settings. - Key Handling: We kept the exact same logic for padding/truncating the key to 24 bytes to ensure compatibility with existing encrypted data.
- IV Validation: 3DES has a 64-bit (8-byte) block size, so CBC mode requires an IV of exactly that length. The check prevents invalid IVs from causing unexpected behavior.
- Padding: Your original function manually implemented PKCS#7 padding, which is the default for
openssl_encrypt(viaOPENSSL_PKCS7_PADDING). We let OpenSSL handle this automatically to simplify code while maintaining compatibility. - Return Value: Using
OPENSSL_RAW_DATAmakesopenssl_encryptreturn raw encrypted bytes, just likemcrypt_genericdid. If your original function returned base64-encoded data, uncomment thebase64_encodeline.
If you need a corresponding decrypt function, you'd use openssl_decrypt with the same cipher, key handling, and IV—just reverse the process!
内容的提问来源于stack exchange,提问作者Aschab
相关产品推荐
相关产品推荐

