How can I encrypt and decrypt the string in PHP?
- User
How can I encrypt and decrypt the string in PHP?
- Assistant
To encrypt and decrypt a string in PHP, a recommended and secure way is to use the
opensslfunctions with a strong cipher method.Here's a simple example using
openssl_encryptandopenssl_decryptwith AES-256-CBC:<?php function encrypt($plaintext, $key) { $cipher = "aes-256-cbc"; // Generate an initialization vector (IV) $ivlen = openssl_cipher_iv_length($cipher); $iv = openssl_random_pseudo_bytes($ivlen); // Encrypt the data $ciphertext_raw = openssl_encrypt($plaintext, $cipher, $key, OPENSSL_RAW_DATA, $iv); // To safely store/send, concat IV with ciphertext and encode with base64 $encrypted = base64_encode($iv . $ciphertext_raw); return $encrypted; } function decrypt($encrypted, $key) { $cipher = "aes-256-cbc"; // Decode from base64 $c = base64_decode($encrypted); // Retrieve the IV length for the cipher method $ivlen = openssl_cipher_iv_length($cipher); // Extract the IV and ciphertext $iv = substr($c, 0, $ivlen); $ciphertext_raw = substr($c, $ivlen); // Decrypt the data $original_plaintext = openssl_decrypt($ciphertext_raw, $cipher, $key, OPENSSL_RAW_DATA, $iv); return $original_plaintext; } // Example usage $key = "thisisaverysecretkey1234567890!!"; // Must be 32 bytes for aes-256-cbc $plaintext = "Hello, encrypt me!"; $encrypted = encrypt($plaintext, $key); echo "Encrypted: " . $encrypted . "\n"; $decrypted = decrypt($encrypted, $key); echo "Decrypted: " . $decrypted . "\n"; ?> - User
I got the following error in my CodeIgniter System: Type: Error
Message: Call to undefined method CI_Loader::decrypt_m()
Filename: /home/u194996331/domains/citrusinno.com/public_html/hkccsa/application/views/admin/pages/forms/login.php
Line Number: 14
Backtrace:
File: /home/u194996331/domains/citrusinno.com/public_html/hkccsa/application/views/admin/login.php Line: 8 Function: view
File: /home/u194996331/domains/citrusinno.com/public_html/hkccsa/application/controllers/admin/Login.php Line: 31 Function: view
File: /home/u194996331/domains/citrusinno.com/public_html/hkccsa/index.php Line: 315 Function: require_once
How can I fix it
- Assistant
- User
How can I make a function in the CodeIgniter view (page) and call it within the file?
- Assistant
- User
How can I hardcode the IV in AES-256-CBC Encryption in PHP?
- Assistant