Tuesday, 14 August 2018

Encrypt data in PHP

Hi all,

Qn) How can I encrypt data in php

Ans: We can simple encrypt the data in php using mcrypt extension.  The functions used are mcrypt_encrypt() and mcrypt_decrypt().

See the program below.

Program courtesy : Sankara Narayana Sharma, MCA III Semester Student, Sree Narayana Institute of Technology, Kollam, Kerala, India.


<html>
<body>

<?php

$input = "Apple";

$encrypted = encryptIt( $input );
$decrypted = decryptIt( $encrypted );

echo "orginal text: ".$decrypted . '<br />'."Encrypted text: " . $encrypted;

function encryptIt( $q ) {
    $cryptKey  = 'rhe';
    $qEncoded      = base64_encode( mcrypt_encrypt( MCRYPT_RIJNDAEL_256, md5( $cryptKey ), $q, MCRYPT_MODE_CBC, md5( md5( $cryptKey ) ) ) );
    return( $qEncoded );
}

function decryptIt( $q ) {
    $cryptKey  = 'rhe';
    $qDecoded      = rtrim( mcrypt_decrypt( MCRYPT_RIJNDAEL_256, md5( $cryptKey ), base64_decode( $q ), MCRYPT_MODE_CBC, md5( md5( $cryptKey ) ) ), "\0");
    return( $qDecoded );
}

?>
</body>


</html>