My problem is this : I have a user id : 0001 And Expiration code : 2015-10-10 12:00
What I need is to encrypt the two value so that I can have some like : TRE-3DR-SER-WER-67J-AX3 (something like this), and also can be decrypted to its original values.
What I did was to jumble the two value, remove spaces and dashes and create a letter or number equivalent to a single character.
My problem is I want the generated kay to be more secure and harder to decode and if possible shorter string.
32 Answers
You should keep the activation key seperate, and irrelevant to expiry date and user ID. It's literally creating a method to decrypt your own keys. Instead; have your table similar to the below.
+----------------------------------------+ | UserID | Key | Expiry | +----------------------------------------+ Than you can generate the ID:
<?php function sernum() { $template = 'XX99-XX99-99XX-99XX-XXXX-99XX'; $k = strlen($template); $sernum = ''; for ($i=0; $i<$k; $i++) { switch($template[$i]) { case 'X': $sernum .= chr(rand(65,90)); break; case '9': $sernum .= rand(0,9); break; case '-': $sernum .= '-'; break; } } return $sernum; } // try it, lets generate 4 serial numbers echo '<pre>'; for ($i=0; $i < 4; $i++) echo sernum(), '<br/>'; echo '</pre>'; ?> Output:
WS41-IZ91-55XO-23WA-WVZS-20VK
SJ42-CV50-79DA-55UV-TERR-28IJ
LY80-CN84-69LV-73EW-ZZEU-09AI
IS86-RG15-39CG-38HK-XLUG-86FO
Then check to see if the generated key is in use (1/1,000,000 chance~)
4Encoding:
$user = "0001"; //Solution only works if this value is always 4 characters. $datetime = "2015-10-10 12:00"; $reps = array("-", " ", ":"); $unencoded = $user . str_replace($reps, "", $datetime); //gives: 001201510101200 $encoded = strtoupper(base64_encode($unencoded)); //This will always be 20 characters long //Result: MDAXMJA5OTK5OTAXMJAW $finalCode = substr($encoded, 0, 5) . "-" .substr($encoded, 4, 5) . "-" .substr($encoded, 9, 5) . "-" .substr($encoded, 14, 5) . "-" //result: MDAXM-JA5OT-K5OTA-XMJAW Decode:
$input = "MDAXM-JA5OT-K5OTA-XMJAW"; $encoded = str_replace("-", "", $input ); $decoded = base64_decode($encoded); $year = substr($decoded, 4, 4); $month = substr($decoded, 8, 2); $day = substr($decoded, 10, 2); $hour = substr($decoded, 12, 2); $min = substr($decoded, 14, 2); $userid = substr($decoded, 0, 4); $date = new DateTime($year . "-". $month . "-" .$day. " ".$hour.":".$min); Note: I would not recommend doing this, it is very insecure. I would follow the advice of some of the other answers and keep your code random and seperate to the user ID and date/time.