Choosing Encryption Extensions and Modes in PHP: mcrypt vs OpenSSL, Algorithms, Key Lengths, and Code Examples
This article explains why PHP7 deprecates the mcrypt extension in favor of OpenSSL, compares DES, 3DES, and AES algorithms, clarifies key length choices, outlines common encryption modes, and provides practical PHP code for encrypting and decrypting data with OpenSSL.
PHP 7 has deprecated the mcrypt extension and recommends using OpenSSL for encryption and decryption tasks.
Among symmetric algorithms, DES is outdated and insecure, 3DES merely repeats DES three times and is also discouraged, while AES (Advanced Encryption Standard) offers high security and performance.
Key lengths are expressed as 128, 192, or 256 bits; for example, a 128‑bit key is 16 bytes such as 1234123412341234. Any bytes beyond the required length are ignored.
Common encryption modes include:
ECB – Electronic Codebook (least secure)
CBC – Cipher Block Chaining (requires an IV, more secure than ECB)
CFB – Cipher Feedback
OFB – Output Feedback
CTR – Counter mode
Example PHP code using OpenSSL:
$my_method = 'aes-128-cbc'; // algorithm
$key = "1234567812345678"; // 128‑bit key
$data = "asxsaxasdlkasjdiqi"; // plaintext
$iv_length = openssl_cipher_iv_length($my_method);
$iv = openssl_random_pseudo_bytes($iv_length, $cstrong);
$enc_data = openssl_encrypt($data, $my_method, $key, OPENSSL_RAW_DATA, $iv); // encrypt
$dec_data = openssl_decrypt($enc_data, $my_method, $key, OPENSSL_RAW_DATA, $iv); // decryptTo view all available cipher methods, run: print_r(openssl_get_cipher_methods()); The output lists methods such as aes-128-cbc, aes-192-cbc, aes-256-cbc, aria-128-cbc, chacha20, des-ede-cbc, and many others.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
