PHP ENCRYPTION USING EXTENDED FUNCTIONS

View previous topic View next topic Go down

PHP ENCRYPTION USING EXTENDED FUNCTIONS

Post by jamied_uk on 27th October 2013, 01:11

Code:

<?php


function encrypt_decrypt($action, $string) {
    $output = false;

    $encrypt_method = "AES-256-CBC";
    $secret_key = 'SuperSecretKey';
    $secret_iv = 'SuperSecret_iv;

    // hash
    $key = hash('sha256', $secret_key);
    $iv = hash('sha256', $secret_iv);

    if( $action == 'encrypt' ) {
        $output = openssl_encrypt($string, $encrypt_method, $key, $iv);
        $output = base64_encode($output);
    }
    else if( $action == 'decrypt' ){
        $output = $decryptedMessage = openssl_decrypt(base64_decode($string), $encrypt_method, $key, $iv);
    }

    return $output;
}

$plain_txt = "This is my plain text";
echo "Plain Text = $plain_txt\n";
?>
<P>
<?php
$encrypted_txt = encrypt_decrypt('encrypt', $plain_txt);
echo "Encrypted Text = $encrypted_txt\n";
?>
<P>
<?php
$decrypted_txt = encrypt_decrypt('decrypt', $encrypted_txt);
echo "Decrypted Text = $decrypted_txt\n";


?>
<P>
<?php
if( $plain_txt === $decrypted_txt ) echo "SUCCESSFULLY DECRYPTED!";
else echo "FAILED";

echo "\n";


/**
 * simple method to encrypt or decrypt a plain text string
 * initialization vector(IV) has to be the same when encrypting and decrypting
 * requires PHP 5 >= 5.3.0
 *
 * this is a beginners template for simple encryption decryption
 * before using this in production environments, please read about encryption
 *
 * @param string $action: can be 'encrypt' or 'decrypt'
 * @param string $string: string to encrypt or decrypt
 *
 * @return string
 */

?>

jamied_uk
Admin

Posts : 1972
Join date : 2010-05-09
Age : 34
Location : UK

http://address-shortner.co.uk

Back to top Go down

View previous topic View next topic Back to top


 
Permissions in this forum:
You cannot reply to topics in this forum