这个是我的注册page其实和login page 差不多。
Register: Client -->Server: username, P<timestamp, H<password>>
一个普通的表单如果直接submit会直接发送明文 不能加密 这样很不安全。在不能实用SSL的情况下 ,我们要在表单发送之前进行加密。
Encrypt: 首先要把表单里的内容传到函数里进行加密: Javascript, HTML
1.把表单数据的button设置 onclick到一个我处理加密的函数senddata();
2.把密码用SHA1计算出hash值 H<password>.
3.把timestamp和密码的hash值用系统的公钥加密 P<timestamp,H<password>>
4.Submit 表单
Decrypt: server接到数据后用私钥解密
1.解密后的信息分解成timestamp和H<psw>.
2.把数据插入数据库里。
<?php
/*
CS683 Step 6
Multi-user server:
register page:
1. Connect to database.
2. Deal with data.
2. Insert new user to database.
*/
if(($_POST['username'])&&($_POST['password'])){
//1. Connect to database.
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("userdatabase", $con);
//2.Set up for information
// get sending username
$username = $_POST['username'];
//get private key and decrypt send password field.
$prifile = file_get_contents('./private.pem');
$prikey = openssl_pkey_get_private($prifile);
openssl_private_decrypt(base64_decode($_POST['password']),$newmessage,$prikey);
//newmessage is the decrpt mesaage. Split into timestamp and sendhpsw
$ents= substr($newmessage, 0, 13);
$sendhpsw = substr($newmessage, 13);
//3. Insert new user to database.
$r = mysql_query("INSERT INTO user(name, password, times) VALUES ('$username', '$sendhpsw', '$ents')");
if(!$r)
echo "please enter again!This username exists.";
}
?>
<html>
<body>
<script type="text/javascript" src="jsbn.js"></script>
<script type="text/javascript" src="rsa.js"></script>
<script type="text/javascript" src="sha1.js"></script>
<script type="text/javascript">
//Encrypt data and then submit.
function senddata(event)
{
//1.Set up for encrypt: get publickey, get form data, H<pwd>, get timestamp.
var pubkeyfile = "-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDcl8ReQc+jTLplbTs2lHhtjAs2h4PM79/vYoqnTQji2Rj05NF2kbM1/e3ZKUK1cIpDnwm9lZG4OS56G+zbj/KfUyj80PmXu5vtgzSc9UZBRdfkdvj0PChmGWBsNk4Q+RwPKFsPVu1P026iNfwhbj89icooZsPITTtEu9wIF+LC0QIDAQAB-----END PUBLIC KEY-----";
var pubkey = RSA.getPublicKey(pubkeyfile);
var getpwd = document.getElementById("password");
var hpwd = sha1(getpwd.value);
var now = new Date();
var timestamp = String(now.getTime());
var data = timestamp + hpwd;
//2.Encrypt P <H(pwd),TS>.
getpwd.value = RSA.encrypt(data, pubkey);
//3. post data
document.loginform.submit();
}
</script>
<h1>Registration for new user</h1>
<form name = "loginform" method="post">
username: <input id = "username" type="text" name="username" />
password: <input id = "password" type="password" name="password" />
<input type="button" value="register" onclick = "senddata(event)" />
</form>
<a href="login.php">Click here to login!!</a>
</body>
</html>