Best PHP Encryption Decryption


Hits: 5701  

I was working on Secured & Expired MP3 Link in HTML5 MP3 Player. Hope you already read previous article “Amazon S3 Expiring Link”

You can use below code for hiding real mp3 link inside html source using base64_encode, mcrypt_encrypt, base64_decode, mcrypt_decrypt and md5.

This function is also useful when you need to secure & expire media links …

Remote Secure Token
Secure Token Plugin with PHP
JavaScript Encryption Library

<?php

function encryptDecrypt($key, $string, $decrypt)
{
    if($decrypt)
    {
        
        $string = str_replace("|", "/", $string);
        
        $decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($string), MCRYPT_MODE_CBC, md5(md5($key))), "12");
        return $decrypted;
    }else{
        $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));        
        
        $stripping = true;
        while ($stripping){
         if(substr($encrypted, -1) == "="){
         $encrypted = substr($encrypted, 0, strlen($encrypted)-1);
        } else {
         $stripping = false;
        }
        }
        return str_replace("/", "|", $encrypted);
    }
}


$echo = encryptDecrypt("123", "http://www.svnlabs.com/mp3/svnlabs1.mp3", 0);
echo $echo."<br>";
echo encryptDecrypt("123", $echo, 1);

?>

 

Output:
yTWxdWnzTqh2OHxrfVX5Xxa+K8vGso9|upjRs+oQJLTDmKNyzVfLCvEcvd3ube|Mk+bxxMpijLjAgusr0EDawQ

Reference: http://commons.oreilly.com/wiki/index.php/PHP_Cookbook/Encryption_and_Security