我的问题是: 我有一个用户ID:0001 和到期代码:2015-10-10 12:00
我需要的是加密这两个值,以便我可以有一些像: TRE-3DR-SER-WER-67J-AX3(类似这样),也可以解密为原始值。
我所做的是混淆两个值,删除空格和破折号,并创建一个等同于单个字符的字母或数字。
我的问题是我希望生成的kay更安全,更难解码,如果可能的话更短的字符串。
答案 0 :(得分:3)
您应该保持激活密钥独立,与失效日期和用户ID无关。它实际上创建了一种解密自己密钥的方法。代替;让你的桌子类似于下面的。
+----------------------------------------+
| UserID | Key | Expiry |
+----------------------------------------+
您可以生成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>';
?>
<强>输出:强>
WS41-IZ91-55XO-23WA-WVZS-20VK
SJ42-CV50-79DA-55UV-TERR-28IJ
LY80-CN84-69LV-73EW-ZZEU-09AI
IS86-RG15-39CG-38HK-XLUG-86FO
然后检查生成的密钥是否正在使用(1 / 1,000,000几率〜)
答案 1 :(得分:-1)
Encoding:
$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.