encrypt decrypt php

function encrypt_decrypt($string, $action = 'encrypt')
{
    $encrypt_method = "AES-256-CBC";
    $secret_key = 'AA74CDCC2BBRT935136HH7B63C27'; // user define private key
    $secret_iv = '5fgf5HJ5g27'; // user define secret key
    $key = hash('sha256', $secret_key);
    $iv = substr(hash('sha256', $secret_iv), 0, 16); // sha256 is hash_hmac_algo
    if ($action == 'encrypt') {
        $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
        $output = base64_encode($output);
    } else if ($action == 'decrypt') {
        $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
    }
    return $output;
}
 
echo "Your Encrypted password is = ". $pwd = encrypt_decrypt('spaceo', 'encrypt');
echo "Your Decrypted password is = ". encrypt_decrypt($pwd, 'decrypt');

4.14
7
Lionel Aguero 33605 points

                                    function encrypt($plaintext, $password) {
    $method = "AES-256-CBC";
    $key = hash('sha256', $password, true);
    $iv = openssl_random_pseudo_bytes(16);

    $ciphertext = openssl_encrypt($plaintext, $method, $key, OPENSSL_RAW_DATA, $iv);
    $hash = hash_hmac('sha256', $ciphertext . $iv, $key, true);

    return $iv . $hash . $ciphertext;
}

function decrypt($ivHashCiphertext, $password) {
    $method = "AES-256-CBC";
    $iv = substr($ivHashCiphertext, 0, 16);
    $hash = substr($ivHashCiphertext, 16, 32);
    $ciphertext = substr($ivHashCiphertext, 48);
    $key = hash('sha256', $password, true);

    if (!hash_equals(hash_hmac('sha256', $ciphertext . $iv, $key, true), $hash)) return null;

    return openssl_decrypt($ciphertext, $method, $key, OPENSSL_RAW_DATA, $iv);
}

//Example usage:
$encrypted = encrypt('Plaintext string.', 'password'); // this yields a binary string

echo decrypt($encrypted, 'password');
// decrypt($encrypted, 'wrong password') === null

4.14 (7 Votes)
0
4.29
7
Awgiedawgie 440220 points

                                    The problem is that in the CryptoJS code a password is used to derive the key and the IV to be used for AES encryption, but mcrypt only uses the key to encrypt/decrypt. This information needs to be passed to php. Since you don't want to transmit the password, you have to derive the key and IV in the same way in php.

The following code derives the key and IV from a password and salt. It is modeled after the code in my answer here (for more information).

function evpKDF($password, $salt, $keySize = 8, $ivSize = 4, $iterations = 1, $hashAlgorithm = "md5") {
    $targetKeySize = $keySize + $ivSize;
    $derivedBytes = "";
    $numberOfDerivedWords = 0;
    $block = NULL;
    $hasher = hash_init($hashAlgorithm);
    while ($numberOfDerivedWords < $targetKeySize) {
        if ($block != NULL) {
            hash_update($hasher, $block);
        }
        hash_update($hasher, $password);
        hash_update($hasher, $salt);
        $block = hash_final($hasher, TRUE);
        $hasher = hash_init($hashAlgorithm);

        // Iterations
        for ($i = 1; $i < $iterations; $i++) {
            hash_update($hasher, $block);
            $block = hash_final($hasher, TRUE);
            $hasher = hash_init($hashAlgorithm);
        }

        $derivedBytes .= substr($block, 0, min(strlen($block), ($targetKeySize - $numberOfDerivedWords) * 4));

        $numberOfDerivedWords += strlen($block)/4;
    }

    return array(
        "key" => substr($derivedBytes, 0, $keySize * 4),
        "iv"  => substr($derivedBytes, $keySize * 4, $ivSize * 4)
    );
}
The salt is generated during encryption in CryptoJS and needs to be sent to php with the ciphertext. Before invoking evpKDF the salt has to be converted to a binary string from hex.

$keyAndIV = evpKDF("Secret Passphrase", hex2bin($saltHex));
$decryptPassword = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, 
        $keyAndIV["key"], 
        hex2bin($cipherTextHex), 
        MCRYPT_MODE_CBC, 
        $keyAndIV["iv"]);
If only encryptedPassword.toString() was sent to the server, then it is necessary to split the salt and actual ciphertext before use. The format is a proprietary OpenSSL-compatible format with the first 8 bytes being "Salted__", the next 8 bytes being the random salt and the rest is the actual ciphertext. Everything together is Base64-encoded.

function decrypt($ciphertext, $password) {
    $ciphertext = base64_decode($ciphertext);
    if (substr($ciphertext, 0, 8) != "Salted__") {
        return false;
    }
    $salt = substr($ciphertext, 8, 8);
    $keyAndIV = evpKDF($password, $salt);
    $decryptPassword = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, 
            $keyAndIV["key"], 
            substr($ciphertext, 16), 
            MCRYPT_MODE_CBC, 
            $keyAndIV["iv"]);

    // unpad (PKCS#7)
    return substr($decryptPassword, 0, strlen($decryptPassword) - ord($decryptPassword[strlen($decryptPassword)-1]));
}
The same can be achieved with the OpenSSL extension instead of Mcrypt:

function decrypt($ciphertext, $password) {
    $ciphertext = base64_decode($ciphertext);
    if (substr($ciphertext, 0, 8) != "Salted__") {
        return false;
    }
    $salt = substr($ciphertext, 8, 8);
    $keyAndIV = evpKDF($password, $salt);
    $decryptPassword = openssl_decrypt(
            substr($ciphertext, 16), 
            "aes-256-cbc",
            $keyAndIV["key"], 
            OPENSSL_RAW_DATA, // base64 was already decoded
            $keyAndIV["iv"]);

    return $decryptPassword;
}

4.29 (7 Votes)
0
3.5
8
Phoenix Logan 186120 points

                                    $decoded = base64_decode($encoded);

3.5 (8 Votes)
0
4
8
Awgiedawgie 440220 points

                                    function encryptor($action, $string) {
	$output = FALSE;
	$encrypt_method = "AES-256-CBC";
	$secret_key = 'SecretKeyWord';
	$secret_iv  = 'SecretIV@123GKrQp';
	// hash
	$key = hash('sha256', $secret_key);
	// iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
	$iv = substr(hash('sha256', $secret_iv), 0, 16);
	//do the encryption given text/string/number
	if ($action == 'encrypt') {
		$output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
		$output = base64_encode($output);
	} elseif ($action == 'decrypt') {
		//decrypt the given text/string/number
		$output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
	}
	return $output;
}

function encrypt($data) {
	return urlencode(self::encryptor('encrypt', self::sanitize($data)));
}

function decrypt($data) {
	return self::encryptor('decrypt', urldecode(self::sanitize($data)));
}
// Now you can just call encrypt($string) or decrypt($string)
?>

4 (8 Votes)
0
4.33
3
Awgiedawgie 440220 points

                                    function encryptPass($password) {
    $sSalt = '20adeb83e85f03cfc84d0fb7e5f4d290';
    $sSalt = substr(hash('sha256', $sSalt, true), 0, 32);
    $method = 'aes-256-cbc';

    $iv = chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0);

    $encrypted = base64_encode(openssl_encrypt($password, $method, $sSalt, OPENSSL_RAW_DATA, $iv));
    return $encrypted;
}

function decryptPass($password) {
    $sSalt = '20adeb83e85f03cfc84d0fb7e5f4d290';
    $sSalt = substr(hash('sha256', $sSalt, true), 0, 32);
    $method = 'aes-256-cbc';

    $iv = chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0);

    $decrypted = openssl_decrypt(base64_decode($password), $method, $sSalt, OPENSSL_RAW_DATA, $iv);
    return $decrypted;
}

4.33 (3 Votes)
0
Are there any code examples left?
Create a Free Account
Unlock the power of data and AI by diving into Python, ChatGPT, SQL, Power BI, and beyond.
Sign up
Develop soft skills on BrainApps
Complete the IQ Test
Relative searches
decode and encode messages decrypt and encrypt php php decrypt and encrypt string php aes decript decrypt crypt function in php decrypt crypt function php php crypt function decrypt php decrypt aes crypt::decrypt php decrypt and encypt in php jsencrypt decrypt with public key in php jsencrypt php decrypt php ecrypt and decrypt php encrypt decrypt text encrypt decrypt php 7 decrypt() php php mysql password encryption decryption php function to encrypt and decrypt message encrypt and decrypt in php decrypt data php str encrypt php how to encrypt and decrypt in php php best password encryption and decryption how encrypt and decrypt password in php php response encrypted payload how to decrypt encrypting and decrypting php php encrypt decrypt integer php encrypt decrypt int can i decrypt encrypted php source code without password salt based encrypt and decrypt using php encrypted decrypt in php how to decrypt password when i encrypt password with sha1]in php make an encryption and decryption in php best function to decrypt password in php php encryption decryption all aes method in php aes in php decrypt php password database php mcrypt_decrypt php code encrypt to decrypt online Decrypt PHP code how to decrypt an encrypted code php password encryption and decryption in php php string encryption and decryption? how to use aes encryption in php how to encrypt password and then decrypt password in php encrypt decrypt id in php decrypt php password how to encrypt string and decrypt string in php encrypt variable in jquery decrypt with php how to decrypt php password php pass encryption make custom encrypt decrypt in php php encrypt and decrypt text encrypt a string using decrypt key in php encrypt decrypt in php php decrypt string encrypted in codeinger 4 php encrypt decrypt id how to do encryotion and decryption in php how to encrypt and decrypt data using pgp javascript php encrypt and decrypt with public key php encrypt decrypt files php encrypt decrypt vs rce encrypt decrypt php encrypt in jquery and decrypt in php php encrypt message encrypt() decrypt php encrypt message crypt() decrypt Encrypt in php decrypt nodejs how decrypt php encrypted string in nodejs decrypt crypt() password in written in php encrypt data with javascript and decrypt data with php php encrypt and decrypt an object aes 256 encryption and decryption in php php encrypt and decrypt data encrypt in php and decrypt in c# how to make a php encryption and decryption code how to encrypt and decrypt password in php using hash php deccyript password file encryption/decryption using php encrypt data on javascript and decrypt it on php password encrypt decrypt php php encry with aes hash encrypt in php decrypt in js how to encryot decrypt php with key core php password encryption and decryption code how to encrypt and decrypt password in php using sha1 core php sql password encryption and decryption core php password encryption and decryption php password encryption and decryption how to use encrypt and decrypt method in php with ajax php simple 10 encrypt and decrypt encryption and decryption algorithm in php encryption in javascript and decryption in php php openssl encrypt and decrypt example php simple encrypt and decrypt algorithm how to encrypt password using php how to decrypt password in php secure way of encrypt/decrypt password in php how to encrypt decrypt in php decrypt function in php encrypt and decrypt php 7 php file decrypt how to encrypt data php and automatically decrypts them encryption and decryption password in php encryption password in php encrypt and decrypt in jquery encrypt in php and decrypt in jquery php encrypt and decrypt password aes encryption in php decrypt crypt() in php Encrypt and decrypt text messages in pure PHP code decript password in php using encrypt encrypt and decrypt password in php mysql decrypt phpbb password android php encrypt decrypt how to encrypt the password in php aes js and php encryption and decryption in php class php custom encryption and decryption in php encrypt using jquery and decypt using php php openssl encrypt decrypt example password encryp php crypt decrypt string php openssl encrypt and decrypt string php php encrypt decrypt string simple how to securely encrypt and decrypt in php decrypt php password hash decrypt password com encrypt php mcrypt_decrypt php hash decrypt php Encryption and decryption project in PHP aes php encryption php encryption password function encrypt decrypt password php php hash encrypt and decrypt php how to encrypt and decrypt a password in php password encrypt php ohow to encrypt and decrypt string in php php encrypt decrypt function encrypt decrypt function in php encrypt and decrypt number in php crypto encrypt and decrypt in php php crypt decrypt php encrypt_decrypt encrpt decrypt php mcrypt_encrypt php 7 how to encrypt and decrypt id in php php password encrypt and decrypt encryption and decryption php project how to decrypt encrypted php code what other methods can i use to encrypt and decrypt a string using php php crypt encrypt decrypt php password encrypt PHP decrypt string with key decrypt crypt password php password encryption php how to encrypt and decrypt password in php using sha256 android encrypt decrypt in php encrypted data php decrypt AES 128 cbc encrypt and decrypt data in php how to encrypt and decrypt password php password decrypt php several methods to encrypt and decrypt a value for php how to encrypt password in php php mcrypt_decrypt example how to encrypt and decrypt password in php mysql php text encrypt decrypt aes algorithm in php decrypt php function simple decrypt php function php encrypt decrypt string database encrypted password decrypted to match in php pass decryptor in php encrypt decrypt file php encrypt and decrypt file php library encrypt and decrypt file php js encrypt php decrypt rsa js encrypt php decrypt password hash decrypt php AES php script php encrypt and decrypt functions openssl encrypt and decrypt php how to decrypt password_hash in php php encrypt password sah1 decrypt in php decrypt with php php ecrypt and decrypt passwords encryption and decryption in php mysql php mysql encrypt decrypt data php simple password encrypt decrypt encrypting and decrypting in php php code for aes encryption and decryption openssl encrypt decrypt php how to decrypt password hash php encrypt decrypt php class php encrypt decrypt for url simple php encrypt decrypt aes encryption and decryption in php example php code to encrypt and decrypt password encrypt and decrypt string in php encrypt data using jquery and decode in php php how to encrypt and decrypt data php mcrypt_encrypt php 7 decrypt encrypted file php encrypting and decrypting data in php how to decrypt A STRING IN PHP Encryption aes php code make own aes php encrypt string in php and decrypt in javascript php hash password decrypt php password decrypt decrypt password in php php simple encrypt decrypt encrypt and decrypt a string in php simple encryption and decryption in php php aes encryption easy php encryption decryption encrypt in js and decrypt in php pgp encryption and decryption php php password hash decrypt php decrypt password encrypt and decrypt password php encrypt_decrypt php encryption decryption in php php how to decrypt password how to decrypt a password in php encrypt in php and decrypt in js how to decrypt php php aes How to encrypt and decrypt password in PHP replace php encrypt decrypt how to decrypt crypt password in php encryption php password encrypt and decrypt password in core php encrypt and decrypt password in php Encrypt with JAVA and Decrypt with PHP aes encryption and decryption in php 5.php decrypt php rijndael encrypt/decrypt custom password encrypt and decrypt php php encrypt and decrypt array php encrypt and decrypt function password encrypt and decrypt in php how to decrypt php hash decrypt password php php encrypt decrypt password php aes method php encrypt decrypt online encrypt in c# and decrypt in php encrypt password in windows form , decrypt in php encrypt decrypt password php encrypt password php array encryption and decryption in php php unsafe encryption how to see a string of encripted password php maintain end to end encryption php how to incrypt decrypt in php aes php '/' is encrypted 2 times in php password encryption and decription in php php encrypter how to encrypt a password in php encryption library php how to encrypt decrypt data in php crypt and decrypt url to 32 characters php hash encryption and decryption in php make encrypted of length 32 php simple encrypt and decrypt in php aes encryption php fast random encryption in php encrypt with key php how to hash and unhash a string in php how to make encrypt decrypt login in php simple encrypt decrypt php function encrypt decrypt php encrypt decrypt text php php simple encrypt and decrypt $ciphertext = base64_encode($ciphertext); add Salted hash with this in php php 2 way encryption with salt how to encrypt password php encrypt decrypt password in php when i decrypt php it gives me something else create encryption library for php php encrypted php how to encrypt text with a salt encryption & decryption php how to encrypt in php what password encryption does laravel use php password decryption encrypt in javascript and decrypt in php encrypt text like php php password_hash decrypt online reversible encryption php how to encrypt small php code password value check geeks for geeks php encryption functions in php word encrypter and decrypter php crypt encrypt php AES decryption in php encrypt decrypt php javascript openssl encrypt php rijndael encryption php 128 by 16 php strong encryptions for strings 2way fixed encryption php php key encryption and decryption encryptIt php ssl encryption php example How to Encrypt and Decrypt a PHP String ? best encrypt decrypt php decrypt to encrypt php online php password encryption php in encript by text not working encripted to text in php php encrypt decrypt with key encrypt and decrypt user password in php encryption and decryption of password in php hash encrypt decrypt php java encrypt decrypt in php decrypt in php bcrypt encrypt and decrypt php encrypted to plain text in not working php php in password to encript simple encrypt decrypt hash protect php php encryption and decryption code openssl decrypt php php two way encrypt decrypt hash password decrypt in php how does php deal with incorect cipher keys hash php decrypt encrypt in php php encode with key how to re encrypt php Encrypt.php crypt and decrypt php how to make encryption in php string and decrypt how to encrypt and decrypt a string in php encrypting passwords in php php encryption php encrypt decrypt length encrypt decrypt password php mysql Function to encrypt or decrypt a string encrypy messages php ciphertext in function doesn't work but out of function does php ciphertext in fucntion doesnt work but out fo fucmtion does php get cipher method from decrepted text in php aes ciphertext decryption information in php with iv and salt length php encrypt string and retrieve by decrypt tools to perform aes 256 encryption php php script to encrypt an input encryption in php password encryption in php php encrypt and decrypt back to text decode php has password into string php decrypt encrypt and decrypt using php encrypt php encryption php encryption and decryption in php example dcrypt and encrypt in php decrypting password in php php incrypt and decrip[t a sting php encrypt to string php crypt to string decrypt encrypt php encrypt value in php aes-256 php save encryption key as text php encrypt string php encrypt how to decrypt in php rijndael_256 cbc 7 padding AES encrypt decrypt in php with salt decrypt php php encrypt unencrypt with key php easily encrypt and decrypt data php string encryption and decryption php encrypt decrypt example cript whit key php encrypt string PHP encrypt text PHP encrpt and decrypt text in php php best encryption and decryption encrypt decrypt string in php php encrypt and decrypt string php encrypt/decrypt php encrypt decrypt hash php encrypt decrypt data encryption and decryption in php php encrypt a string php encrypt and decrypt with key how to do encrypt and decrypt in php encrypt and decrypt string php php encrypt and decrypt PHP can encrypt data what that means encrypt in php and decrypt in php php hash encrypt decrypt php encrypt decrypt encrypt string in php encrypt and decrypt php encryption and decryption php php encrypting crypt and decrypt php 5.6 encrypt en decrypt php php encrypt text add encryption to text in php encrypt and decrypt in php encrypt and decrypt function in php with a key php text encription
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source