Search code examples
phplicense-key

Encrypt and decrypt a license key in PHP


I need to generate a license key with a given name, product title and an expiry date. If one of my customers buys my product and uses it, he has to enter this license key.

I tried so much methods and I have no clue how to achieve this in PHP. The key should be safe for reproduction. What would be the best way to create a license key encryption and decryption in PHP?


Solution

  • The below code may help you:

    function encrypt($sData, $secretKey){
        $sResult = '';
        for($i=0;$i<strlen($sData);$i++){
            $sChar    = substr($sData, $i, 1);
            $sKeyChar = substr($secretKey, ($i % strlen($secretKey)) - 1, 1);
            $sChar    = chr(ord($sChar) + ord($sKeyChar));
            $sResult .= $sChar;
    
        }
        return encode_base64($sResult);
    } 
    
    function decrypt($sData, $secretKey){
        $sResult = '';
        $sData   = decode_base64($sData);
        for($i=0;$i<strlen($sData);$i++){
            $sChar    = substr($sData, $i, 1);
            $sKeyChar = substr($secretKey, ($i % strlen($secretKey)) - 1, 1);
            $sChar    = chr(ord($sChar) - ord($sKeyChar));
            $sResult .= $sChar;
        }
        return $sResult;
    }
    
    function encode_base64($sData){
        $sBase64 = base64_encode($sData);
        return str_replace('=', '', strtr($sBase64, '+/', '-_'));
    }
    
    function decode_base64($sData){
        $sBase64 = strtr($sData, '-_', '+/');
        return base64_decode($sBase64.'==');
    }
    

    Here

    $secretKey; // Your secret key can be anything which you only know it. So no one easily decrypt through any tool. (recommended often change the $secretKey).