简体   繁体   中英

Php code to encrypt client input data and decrypt it at the server side

I want to encrypt password and confirm password field at the client side and after it reaches to the server side via some network it should be decrypted to it's original form again.

Below is the code of a javascript file (enc.js) that i wrote which will encrypt data at the client side. I am unable to decrypt it at the server side.

$(document).ready(function()
{ $("#login_submit").click ( 

        function()
        {
            var password=$("#password").val();
            var pass=CryptoJS.MD5(password).toString();
            var q=$("#salt").val();
            var encp = CryptoJS.MD5(q + pass).toString();
            $("#password").attr('value', encp);
        });
}); 

The above code is working absolutely fine, but i need some help to decrypt the encrypted data at the server side which has been encrypted using CryptoJS.MD5() at the client side.

Below is the code of clent side web page (register.php)

<?PHP
session_start();
session_regenerate_id(true);
if(!isset($_SESSION['user']))
{
header("location:../login/log.php");
}
else if(($_SESSION['user']) != "admin")
{
echo "<br><br>";
header( "refresh:3; url=nopage.php" );
echo "<center>Access Denied</center>";
echo "<center><a href='nopage.php'>Back</a></center>";
}
else
{
require_once("./include/membersite_config.php");
include_once "../validation/Validator.php"; 
require("../connection123.php");   
$protocol = strpos(strtolower($_SERVER['SERVER_PROTOCOL']),'https') 
=== FALSE ? 'http' : 'https';
$host     = $_SERVER['HTTP_HOST'];
$script   = $_SERVER['SCRIPT_NAME'];
$params   = $_SERVER['QUERY_STRING'];
$currentUrl = $protocol . '://' . $host . $script . '?' . $params;
$head=$v->valHeader($currentUrl);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
<head>
<meta http-equiv="Cache-Control" content="no-cache"/>
<meta http-equiv="Cache-Control" content="no-store"/>
<meta http-equiv="Cache-Control" content="must-revalidate"/>
<meta http-equiv="Cache-Control" content="private"/>
<meta http-equiv="Cache-Control" content="pre-check=0"/>
<meta http-equiv="Cache-Control" content="post-check=0"/>
<meta http-equiv="Cache-Control" content="max-stale=0"/>
<meta http-equiv="Pragma" content="no-cache"/>
<meta http-equiv="Expires" content="Mon, 26 Jul 1997 05:00:00 GMT"/>
<link rel="STYLESHEET" type="text/css" href="style/fg_membersite.css" />
<script type='text/javascript' src='scripts/gen_validatorv31.js'></script>
<link rel="STYLESHEET" type="text/css" href="style/pwdwidget.css" />
<script src="scripts/pwdwidget.js" type="text/javascript"></script> 
<script type="text/javascript">
window.history.forward();
       function noBack(){window.history.forward()}
       noBack();
       window.onload=noBack;
       window.onpageshow=function(evt){if(evt.persisted)noBack()}
       window.onunload=function(){void(0)}
</script>
<script type="text/javascript" language="javascript" src="../js/jquery-1.8.3.js"></script>
<script type="text/javascript" language="javascript" src="../js/jquery_md5.js"></script>
<script type="text/javascript" language="javascript" src="../js/md5.js"></script>
<script type="text/javascript" language="javascript" src="../js/enc.js"></script>
</head>
<body bgcolor="#FFFFCC">
<?php
$current_url = $_SERVER['REMOTE_ADDR'].$_SERVER['PHP_SELF'];
$v=new validator();
                            error_reporting(0);
                            $url=$_SERVER['HTTP_REFERER'];
                            $headerAdd=$v->valHeader($url);
                            $salt = substr(md5(uniqid(rand(), true)), 0, 32);
?>
<div align="left">
<table width="1214" border="0">
<tr>
<td width="867"><a href='login-home.php'>Back</a></td>
<?php
// make a random id
$_SESSION["token"] = md5(uniqid(mt_rand(), true));
echo '<td width="331"><a href="logout.php?csrf=' . $_SESSION["token"] .    '">Logout</a></td>';

?>
</tr>
</table>
</div>
<?php
$token= md5(uniqid());
$_SESSION['delete_customer_token']= $token;
session_write_close();
?>
<br /><br />
<!-- Form Code Start -->
<div id='fg_membersite'>
<form id='register' name='register' action='afterregister.php' method='post'  accept-charset='UTF-8'>
<fieldset >
<legend>Register New Account Here</legend>
<div class='short_explanation'>* Required fields</div>
<div><span class='error'><?php echo $fgmembersite->GetErrorMessage(); ?>
</span></div>
<div class='container'>
<input type="hidden" name="token" value="<?php echo $token; ?>" />
<input type="hidden" name="registeracct" value="Register Account" />
<label for='name' >Your Full Name*: </label><br/>
<input type='text' name='name' id='name' value='' maxlength="30" autocomplete="off" /><br/>
<span id='register_name_errorloc' class='error'></span>
</div>
<div class='container'>
<label for='username' >UserName*:</label><br/>
<input type='text' name='username' id='username' value='' maxlength="30"   autocomplete="off"/><font-color='#FF0000'>[Only letters without space]</font>
<input id="salt" type="hidden" name="salt" maxlength=50 value=<?php echo $salt;?>/>
<br/>
<span id='register_username_errorloc' class='error'></span>
</div>
<div class='container' style='height:80px;'>
<label for='username' >Email id*:</label><br/>
<input type='text' name='email' id='email' value='' maxlength="300"  autocomplete="off"/><br/>
<label for='p_word' >Password*:</label><br/>
<div class='pwdwidgetdiv' id='thepwddiv' ></div>
<noscript>
<input type='password' name='password' id='password' maxlength="30" autocomplete="off" />
</noscript>    
<div id='register_password_errorloc' class='error' style='clear:both'></div>
<label for='p_word' >Confirm Password*:</label><br/>
<div class='pwdwidgetdiv' id='cnfpwddiv' ></div>
<noscript>
<input type='password' name='cnpwd' id='cnpwd' maxlength="30" autocomplete="off" />
</noscript>    
<div id='register_password_errorloc' class='error' style='clear:both'></div> 
<br/>
</div><br/>
<br/>
<br/>
<br/>
<div class='container'>
<input type="submit" id="login_submit" name="Submit" value="Submit" />
</div>
</fieldset>
</form>
<script type='text/javascript'>
// <![CDATA[
var pwdwidget = new PasswordWidget('thepwddiv','password');
pwdwidget.MakePWDWidget();
var pwdwidget = new PasswordWidget('cnfpwddiv','cnpwd');
pwdwidget.enableGenerate = false;
pwdwidget.MakePWDWidget();
var frmvalidator  = new Validator("register");
frmvalidator.EnableOnPageErrorDisplay();
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name","req","Please provide your name");
frmvalidator.addValidation("username","req","Please provide a username");
frmvalidator.addValidation("email","req","Please provide a email-id");
frmvalidator.addValidation("password","req","Please provide a password");
frmvalidator.addValidation("cnpwd","req","Please re-enter password");
// ]]>
</script>
</body>
</html>
<?php
} 
?>


Below is the code of server side (afterregister.php)

<?php
session_start();
session_regenerate_id(true);
$s_id=session_id();//PHPSESSID
error_reporting(0);
require("../connection123.php");
include_once "../validation/Validator.php";
include_once "../validation/val.php";
$v=new Validator();
if(mysqli_connect_errno())
{
echo "Connection Failed: " . mysqli_connect_errno();
  exit();
}
$array=array('token','registeracct','name','username','salt','email','password','cnpwd','Submit');
$n=$v->array_equal($_POST,$array);
if($n!=0){
         $redirect="../nopage.php";
    die('<script type="text/javascript">window.location.href="' . $redirect . '";</script>');
  }
    $ip="";
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {   //check ip from share internet
        $ip1 = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {   //to check ip is pass from proxy
        $ip1 = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip1 = $_SERVER['REMOTE_ADDR'];
    if(filter_var($ip1,FILTER_VALIDATE_IP)){
        $ip=$ip1;
    }else{
    header("location:../nopage.php");
    }
    }

    $formname="";
    if(isset($_POST['registeracct']))
    {
       $formname= $_POST['registeracct'];
    }
    $token = $_SESSION['delete_customer_token'];
    unset($_SESSION['delete_customer_token']);
    session_write_close();
    //echo $formname;
    $stmt = $mysqli -> prepare("SELECT logindt FROM tblaudit ORDER BY logindt DESC LIMIT 1");

        $stmt-> execute();
        $stmt->store_result();
        $stmt-> bind_result($result1);
        $login="";
       if($stmt->fetch())
       {
         $login=$result1;
       }
//echo $login;
    //echo $ip;

    $name1=$v->validateSQLInjectionlogin($_POST['name']);
    $name2=$v->xss_protect($name1);
    $name=$v->validf_name($name2);
    //echo $name;
/** if($name==""){
        $redirect="../nopage.php";
        die('<script type="text/javascript">window.location.href="' . $redirect . '";</script>');
    }**/

    $name1=$v->validateSQLInjectionlogin($_POST['username']);
    $usernamee=$v->xss_protect($name1);
    $username=$v->validf_name($usernamee);

    //echo $username;

    $salt1=$v->validateSQLInjectionlogin($_POST['salt']);
    $salt=$v->xss_protect($salt1);

    $email="";
    if(isset($_POST['email']))
    {
    $email= $_POST['email'];
    }

    //echo $email;          

    $name1=$v->validateSQLInjection($_POST['password']);
    $password=$v->xss_protect($name1);


    //$pass=md5($salt . md5($password));
    $pass=md5($password);

    //echo $pass;

    $cnfpwd1=$v->validateSQLInjection($_POST['cnpwd']);
    $cnfpwd=$v->xss_protect($cnfpwd1);

    //echo $cnfpwd;
    $no='no';

    $confirmcode = 'y';

    $stmt1 = $mysqli -> prepare("SELECT distinct username FROM users WHERE username=?");
    $stmt1->bind_param("s", $username);
    $stmt1->execute();
    $stmt1->store_result();
    $stmt1-> bind_result($result2);



    $stmt5 = $mysqli -> prepare("SELECT distinct email FROM users WHERE  email=?");
    $stmt5->bind_param("s", $email);
    $stmt5-> execute();
    $stmt5->store_result();
    $stmt5->bind_result($result3);

    /** if($formname=="" or $name=="" or $username=="" or $salt=="" or $password=="" or $cnfpwd=="" )
    {
         $redirect="../nopage.php";
         die('<script type="text/javascript">window.location.href="' . $redirect . '";</script>');
    }**/
if ($token && $_POST['token']==$token) 
{
    if($stmt1->fetch()) 
    {
      echo "<br><br>";
      echo "<center>Username already exists. Please provide a unique username</center>";
      echo "<center><a href='register.php'>Back</a></center>";

      $stmt1->close();

    } 
    else if (strlen($username) < 5 OR strlen($username) > 20) 
    {
      echo "<br><br>";
      echo "<center>Username should be within 5-20 characters long.</center>";
      echo "<center><a href='register.php'>Back</a></center>";

    }
    elseif(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/i", $email))
    {
      echo "<br><br>";
      echo "<center>Enter a valid Email-id.</center>";
      echo "<center><a href='register.php'>Back</a></center>";

    }
    elseif($stmt5->fetch())
    {
      echo "<br><br>";
      echo "<center>Email-id already exists. Please provide a unique email-id</center>";
      echo "<center><a href='register.php'>Back</a></center>";

      $stmt5->close();
    }
    else if (!preg_match('/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/', $password))
    {
      echo "<br><br>";
      echo "<center>Password should contain minimum 8 characters, atleast an uppercase letter, a lowercase letter and a number.</center>";
      echo "<center><a href='register.php'>Back</a></center>";

    }
    else if($password != $cnfpwd)
    {
              echo "<br><br>";
              echo "<center>Confirm password not matched!</center>";
              echo "<center><a href='register.php'>Back</a></center>";
    }
    else
    {
        $stmt2 = $mysqli->prepare("insert into users(name,username,email,password,confirmcode,locked) values(?,?,?,?,?,?)");
        $stmt2->bind_param('ssssss',$name,$username,$email,$pass,$confirmcode,$no);
        $stmt2->execute();


        $stmt3=$mysqli->prepare("insert into session(id,username,salt,session_id) values(?,?,?,?)");
        $stmt3->bind_param('ssss',$ip,$username,$salt,$s_id);
        $stmt3->execute();

        // create the audit trail
        //$stmt4 = $mysqli->prepare("insert into tblaudit (uID,editor,formname,whenpost,ip) values(?,?,?,NOW(),?)");
        //$stmt4->bind_param('ssss',$userid,$editor,$formname,$ip);
        //$stmt4->execute();


        $stmt4=$mysqli->prepare("update tblaudit set formname=?, whenpost= NOW() where logindt=?");
        $stmt4->bind_param('ss',$formname,$login);
        $stmt4->execute();


        include "thank-you-regd.html";


        $stmt2->close();
        $stmt3->close();
        $stmt4->close();

        $mysqli->close();


    }
}
else
{
   echo "unable to register a new account";
}
?>

Understanding SSL

SSL (Secure Sockets Layer) is the standard security technology for establishing an encrypted link between a web server and a browser. This link ensures that all data passed between the web server and browsers remain private and integral.

However, you can create your own ( useless ) encryption but i recommend you use SSL .

Types of encryption: https://support.microsoft.com/en-us/kb/246071

  • asymmetric encryption - Symmetric encryption is the oldest and best-known technique. A secret key, which can be a number, a word, or just a string of random letters, is applied to the text of a message to change the content in a particular way. This might be as simple as shifting each letter by a number of places in the alphabet. As long as both sender and recipient know the secret key, they can encrypt and decrypt all messages that use this key.

  • symmetric encryption - here are two related keys--a key pair. A public key is made freely available to anyone who might want to send you a message. A second, private key is kept secret, so that only you know it.

asymmetric and symmetric encryption work together to create a SSL encryption to communicate from the client to the server.

It is highly advised you do not attempt to reinvent the wheel, use SSL. any encryption you write on the client side can easily be cracked because JavaScript is readable.


Hashing vs Encryption

MD5 (message-digest algorithm) - sa widely used cryptographic hash function producing a 128-bit (16-byte) hash value, typically expressed in text format as a 32 digit hexadecimal number. MD5 has been utilized in a wide variety of cryptographic applications, and is also commonly used to verify data integrity.

Hashing & encryption are entirely different terminologies. Hashing is one way, and may have several alternative patterns that match. Encryption is reversible with a key. read more here: http://www.securityinnovationeurope.com/blog/whats-the-difference-between-hashing-and-encrypting


Understanding Javascript

Javascript - is a high level, dynamic, untyped, and interpreted programming language. It has been standardized in the ECMAScript language specification.

JavaScript is not meant to manage security. JavaScript is mainly meant for DOM ( Document Object Model ) manipulation & a few other related manipulations. Though, it does have some capabilities outside the scope of the DOM .

Unfortunately client side javascript source code is widely open for everyone to see and examine. You simply right click and press "view source..." or use firebug or something else.

In addition, every unsecured http request (via http and not https = ssl) is sent as a readable unencrypted string and can be monitored from other devices in your network.

Both of the above mean that you actually shouldnt MD5 your user + pass in client side js prior to sending them to the server because it really doesnt matter as users can view your js source code anyway and deduce your salt and arrangement of the string to be hashed. So it really wont matter if you send the user + pass without any encryption.

To facilitate encryption Id advise you to purchase a ssl plan from your hosting company (like godaddy) and make sure they install it for you. Then, its only a matter of navigating to your site via https.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM