Showing posts with label encryption. Show all posts
Showing posts with label encryption. Show all posts

Friday, 19 September 2014

PHP: Create big unique ID like Facebook or MongoDB

Most of web application using a relational database management system (MSQL, SQL ..etc) to store data as records. We need an unique id to use as a key Primary.
How to do it ?
* SQL AUTO INCREMENT a Field :
--> 1,2,3,4,5..... #anyone can count the number of your records and more

* PHP uniqid :
--> 541cf7f7d685e, 541cf7f7d685e, 541cf7f7d685e .....  #somewhat similar?

* Or use a custom function like this :

function gen_id() {
    return sprintf( '%04x%04x%04x%04x%04x%04x%04x%04x',
        // 32 bits for "time_low"
        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),

        // 16 bits for "time_mid"
        mt_rand( 0, 0xffff ),

        // 16 bits for "time_hi_and_version",
        // four most significant bits holds version number 4
        mt_rand( 0, 0x0fff ) | 0x4000,

        // 16 bits, 8 bits for "clk_seq_hi_res",
        // 8 bits for "clk_seq_low",
        // two most significant bits holds zero and one for variant DCE1.1
        mt_rand( 0, 0x3fff ) | 0x8000,

        // 48 bits for "node"
        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
    );
}
Result : 6800cd499f25434aac48c0bb51f46307, caa02c4831194690ad8458c3a4e07a0c, 7488a4c459d64f8dbacd2b79f44ed4bf ......

- differences
- professional (like facebook, google, MongoDB ...)
high performance
- unrestricted

Reference : PHP uuid lib

Wednesday, 4 September 2013

PHP AES encrypt / decrypt

$sDecrypted and $sEncrypted were undefined in your code. See fixed solution:
$Pass = "Passwort";
$Clear = "Klartext";        

$crypted = fnEncrypt($Clear, $Pass);
echo "Encrypred: ".$crypted."</br>";

$newClear = fnDecrypt($crypted, $Pass);
echo "Decrypred: ".$newClear."</br>";        

function fnEncrypt($sValue, $sSecretKey)
{
    return rtrim(
        base64_encode(
            mcrypt_encrypt(
                MCRYPT_RIJNDAEL_256,
                $sSecretKey, $sValue, 
                MCRYPT_MODE_ECB, 
                mcrypt_create_iv(
                    mcrypt_get_iv_size(
                        MCRYPT_RIJNDAEL_256, 
                        MCRYPT_MODE_ECB
                    ), 
                    MCRYPT_RAND)
                )
            ), "\0"
        );
}

function fnDecrypt($sValue, $sSecretKey)
{
    return rtrim(
        mcrypt_decrypt(
            MCRYPT_RIJNDAEL_256, 
            $sSecretKey, 
            base64_decode($sValue), 
            MCRYPT_MODE_ECB,
            mcrypt_create_iv(
                mcrypt_get_iv_size(
                    MCRYPT_RIJNDAEL_256,
                    MCRYPT_MODE_ECB
                ), 
                MCRYPT_RAND
            )
        ), "\0"
    );
}