根据id生成唯一邀请码并加密

推广程序中会使用邀请码,直接使用表id作为邀请码并不好,先实现根据id生成唯一邀请码并加密的方式提供邀请码

参考

参考链接如下:

https://www.php.cn/php-weizijiaocheng-388405.html

改进

如参考方式可进行10进制转35进制进行生成邀请码,用户填写邀请码后即可通过解码(转10进制)得到用户ID,但此种方式生成的邀请码依旧会存在很强的规律,容易被猜出

如:id从11到21

000B
0001
000N
000O
000P
000I
000J
0002
000R
000S

对于此可进行简单加密操作,如

function eyz_encode_open_id($user_id) {
    //先转成35进制
    static $source_string = 'E5FCDG3HQA4B1NOPIJ2RSTUV67MWX89KLYZ';
    $user_id = $user_id;
    $code = '';
    while ( $user_id > 0) {
        $mod = $user_id % 35;
        $user_id = ($user_id - $mod) / 35;
        $code = $source_string[$mod].$code;
    }
    if(empty($code[3]))
        $code = str_pad($code,4,'0',STR_PAD_LEFT);
    return $code;
    //加密
    $lastChar = substr($code, -1);
    $step = strpos($source_string,$lastChar) - 1 ;
    $strLen = strlen($code);
    for ($i=0;$i<$strLen-1;$i++){
        if($step%2)
            $local = strpos($source_string,$code[$i])+$step-$i;
        else
            $local = strpos($source_string,$code[$i])+$step+$i;
        if ($local < 0)
            $local = 35 + $local;

        if($local >= 35 ){
            $local = $local - 35;
        }
        $code[$i] = $source_string[$local];
    }
    return $code;
}

加密后id从11到21如下:

4B1B
B4A1
1NON
N1BO
OPIP
PONI
IJ2J
JIP2
2RSR
R2JS

此种方式则没有可见的规律可言,也可使用此方式生成的码作为向外展示用户的唯一码

附解码函数:

function eyz_decode_open_id($code) {
    static $source_string = 'E5FCDG3HQA4B1NOPIJ2RSTUV67MWX89KLYZ';
    //解密
    $lastChar = substr($code, -1);
    $step = strpos($source_string,$lastChar) - 1 ;
    $strLen = strlen($code);

    for ($i=0;$i<$strLen-1;$i++){
        if($step%2)
            $local = strpos($source_string,$code[$i])-$step+$i;
        else
            $local = strpos($source_string,$code[$i])-$step-$i;

        if ($local < 0)
            $local = 35 + $local;

        if($local >= 35 ){
            $local = $local - 35;
        }
        $code[$i] = $source_string[$local];
    }
    //进制转换为10进制
    if (strrpos($code, '0') !== false)
        $code = substr($code, strrpos($code, '0')+1);
    $len = strlen($code);
    $code = strrev($code);
    $num = 0;
    for ($i=0; $i < $len; $i++) {
        $num += strpos($source_string, $code[$i]) * pow(35, $i);
    }
    return $num;
}
admin

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: