Skip to content

Instantly share code, notes, and snippets.

@kice
Last active August 29, 2015 13:57
Show Gist options
  • Save kice/9684445 to your computer and use it in GitHub Desktop.
Save kice/9684445 to your computer and use it in GitHub Desktop.
URL登录-PHP
<?php
include('connet.php');
/**
* URL Login Class
* URL登录
* 使用RSA加密算法
*
* Copyright Kice
**/
class URLLogin
{
/* 原理:
获得登录链接
1、生成一对RSA密钥
2、生成一个需要加密的字符串(生成时间+帐号密码+一个随机字符串+一个固定字符串)
3、用私钥加密字符串,生成URL(调用GetLoginURL())
4、保存公钥,时间,随机字符串
验证登录链接
1、获得保存公钥,时间,随机字符串
2、检查是否超时(暂定600秒)
3、验证签名(通过访问URL获得签名)
4、返回结果
*/
private $pubkey;
private $prikey;
private $time;
private $pass;
public function __construct()
{
$this->time = time();
}
// 如果需要更改保存信息的方法,修改这个函数
private function SaveVerifyInfo()
{
// 保存验证信息
$sql = "INSERT INTO `url_login` (
`id` ,
`time` ,
`publickey` ,
`password`
)
VALUES (
NULL , '".$this->time."', '".$this->base64url_encode($this->pubkey)."', '".$this->base64url_encode($this->pass)."'
);";
mysql_query($sql);
$id = mysql_insert_id();
// 这里是返回一个登录ID
return $id;
}
// 如果需要更改读取信息的方法,修改这个函数
private function GetVerifyInfo($id)
{
// 根据登录ID获取验证信息
$sql = "SELECT * FROM `url_login` WHERE `id` = ".$id;
$r = mysql_query($sql);
$result = mysql_fetch_array($r);
$this->time = $result['time'];
$this->pubkey = $this->base64url_decode($result['publickey']);
$this->pass = $this->base64url_decode($result['password']);
}
private function InitRSA()
{
// 初始化
$res = openssl_pkey_new();
openssl_pkey_export($res,$pri);
$data = openssl_pkey_get_details($res);
$this->pass = $this->CreatePassword();
$this->prikey = $pri;
$this->pubkey = $data['key'];
}
private function CreatePassword($pw_length = 8)
{
$randpwd = '';
for ($i = 0; $i < $pw_length; $i++)
{
$randpwd .= chr(mt_rand(33, 126));
}
return $randpwd;
}
private function base64url_encode($data)
{
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
private function base64url_decode($data)
{
return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
}
private function GetUnsignData($password)
{
return ($this->time.$password.$this->pass."dlgmISdbRDpYTkNEUGN9Pl1JfVtbfU1jSml7ZTB6UjI=");
}
public function GetLoginURL($password, $verifyUrl)
{
// 获得登录的URL
/*
下面是测试用的
$password = '6*VG$*BRSj@SBMzk';
$verifyUrl = "verify.php";
*/
$this->InitRSA();
$data = $this->GetUnsignData();
openssl_sign($data, $signature, $this->prikey);
$signature = $this->base64url_encode($signature);
$id = $this->SaveVerifyInfo();
$url = $verifyUrl."?id=".$id."&sign=".$signature;
return $url;
}
public function CheckLoginURL($signature, $id, $password)
{
$this->GetVerifyInfo($id);
// 验证是否为合法的登录请求
$checkTime=time();
if ($checkTime - $this->time > 600) {
exit("登录超时");
}
$publickey = $this->pubkey;
$data = $this->GetUnsignData();
$signature = $this->base64url_decode($signature);
$r = openssl_verify($data, $signature, $publickey);
return $r;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment