This question already has answers here:
encrypt and decrypt md5
(6 answers)
Closed 5 years ago.
I am sharing my 2 file's code.for insert username and passwords and to retrieve data. My scenario is something different. if username :
abc and password: 123456789
on login screen user have to enter only 3 digits from his password.But that will be random numbers from his password. if now system will ask me for 1st,3rd and 9th digit from password.after reload page it will change randomly. it will display 2nd,5th and 4th etc etc.
I am done this task earlier with my code. but now i am thinking to insert password with md5 encryption method.
I am stuck here if i used md5 for encryption then how to retrive password.
insert.php :
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="" method="post">
<label>username</label>
<input type="text" name="username">
<label>pin</label>
<input type="password" name="pin">
<label>password</label>
<input type="password" name="password">
<button name="submit">Submit</button>
</form>
</body>
</html>
<?php
include 'conn.php';
if (isset($_POST['submit']))
{
$name = $_POST['username'];
$pass = md5($_POST['password']);
$sql = mysqli_query($conn,'INSERT INTO `emp`(`name`, `pass`) VALUES ("'.$name.'","'.$pass.'")');
if ($sql>0)
{
header('Location: index.php');
}
}
?>
index.php:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
include 'conn.php';
if (isset($_POST['submit'])) {
$name = $_POST['username'];
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
$pass3 = $_POST['pass3'];
$char1 = $_POST['char1'];
$char2 = $_POST['char2'];
$char3 = $_POST['char3'];
$sql = 'SELECT name,pass,pin from `emp` '
. 'where `name` = "'.$name.'" '
. 'AND SUBSTR(pass, '.($char1).', 1) = \''.$pass1.'\' '
. 'AND SUBSTR(pass, '.($char2).', 1) = \''.$pass2.'\' '
. 'AND SUBSTR(pass, '.($char3).', 1) = \''.$pass3.'\' ';
$sql = mysqli_query($conn,$sql);
$data = mysqli_fetch_assoc($sql);
if ($data)
{
echo 'success';
}
else
{
echo 'Fail';
}
}
// generate unique, not equal numbers
$char_pos = range(1, 9);
shuffle($char_pos);
$char_pos = array_slice($char_pos, 0, 3);
sort($char_pos);
?>
<form action="" method="post">
<input type="hidden" name="char1" value="<?php echo $char_pos[0]; ?>">
<input type="hidden" name="char2" value="<?php echo $char_pos[1]; ?>">
<input type="hidden" name="char3" value="<?php echo $char_pos[2]; ?>">
Username:
<input type="text" name="username" value="">
Password:
<input type="password" class="inputs" maxlength="1" name="pass1" placeholder='<?php echo $char_pos[0]; ?>st' value="">
<input type="password" class="inputs" maxlength="1" name="pass2" placeholder='<?php echo $char_pos[1]; ?>th' value="">
<input type="password" class="inputs" maxlength="1" name="pass3" placeholder='<?php echo $char_pos[2]; ?>th' value="">
<button name="submit">Submit</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(".inputs").keyup(function () {
if (this.value.length == this.maxLength) {
$(this).next('.inputs').focus();
}
});
</script>
</body>
</html>
MD5() function is not a encrypt decrypt function. it produce data based on input. That data cannot be reverted. if you need to check MD5 output with ordinary text, you have to MD5 ordinary text then compare both MD5 output.
There are several Online MD5 Decrypter present. It is based on Past input history.
www.md5online.org
md5decrypt.net/en/
You can check with this ..
Thank you...
As already pointed out in comments, md5 is a one-way hash function, not an encryption. This means that it is impossible to perform a partial password verification against the hash because the original password cannot be retrieved.
The Smart Architects blog used to have a great article on partial password verification, but now it is only accessible via web archive.
To sum up the possibilities (omitting the completely unsecure storing password in plain text solution):
Store the passwords in an encrypted format, meaning you can retrieve the password in plain text if needed for comparison. Pro: easy to implement. Con: if someone obtains the key, then all passwords can be reversed. If you want something really secure, then you probably need an HSM (Hardware Security Module) for this. Until you get your hands on an HSM, you can try openssl_encrypt() function.
Hash all combination of letters the interface may ask in a hashed format. Pro: probably the most secure storage format (if the right hashing algorithm is used with salts). Con: just think about the number of records you need to create for a long password.
Use Shamir secret sharing scheme. Pro: compromise in storage space vs security. Con: probably the most difficult solution to implement from a coding perspective.
Related
The following PHP code is for generating a random number of four digits ($numero) and using it as a validation for a simple HTML form with three input boxes. The last input box is for entering the code (the random number). If the user doesn't write the right number in that last input box the program skips its purpose, which is adding some text to a database (agregar.txt). I think the code is fine, except for if ($_POST['password'] != $numero) {. Should I change it to a string or use another kind of variable? Each time I run the code it acts as if $numero was different from password, and I'm sure I'm writing the right number. Please some help.
<html>
<body>
<center>
<h2>Agregar entradas a diccionarioie</h2>
<?php
// RANDOM FOUR DIGITS NUMBER
$numero = rand(1000, 9999);
echo "<b>Código: </b><big>".$numero."</big><p>";
if ($_POST['password'] != $numero) {
?>
<form name="form" method="post" action="">
<input title=" LEMA " size="30" type="text" name="lema" autofocus><br>
<input title=" TRADUCCIÓN " size="30" type="text" name="trad"><br>
<input title=" CÓDIGO " size="30" type="text" name="password"><br>
Gracias por colaborar <input title=" ENVIAR " type="submit" value="•"></form>
<?php
} else {
$lema = $_POST['lema'];
$trad = $_POST['trad'];
// ADDING TEXT TO A DATABASE
$texto = $lema." __ ".$trad."\n";
$docu = fopen("agregar.txt", "a+");
fwrite($docu, $texto);
fclose($docu);
}
?>
</center>
</body>
</html>
As pointed out by #Fred -ii-, the problem in your code is the $numero get generated to different random number when you submit the form. The solution is to use session: PHP session example
The session can be used to store your $numero value after the form being submitted. Here's the updated code:
<?php
// Make sure to start the session before any output.
session_start();
if (isset($_POST['password']) && isset($_SESSION['numero']) && $_POST['password'] == $_SESSION['numero']) {
unset($_SESSION['numero']);
$lema = $_POST['lema'];
$trad = $_POST['trad'];
// ADDING TEXT TO A DATABASE
$texto = $lema." __ ".$trad."\n";
$docu = fopen("agregar.txt", "a+");
fwrite($docu, $texto);
fclose($docu);
} else {
// RANDOM FOUR DIGITS NUMBER & STORE IT IN SESSION.
$numero = $_SESSION['numero'] = rand(1000, 9999);
?>
<html>
<body>
<center>
<h2>Agregar entradas a diccionarioie</h2>
<b>Código: </b><big><?php echo $numero; ?></big><p>
<form name="form" method="post" action="">
<input title="LEMA " size="30" type="text" name="lema" autofocus><br>
<input title="TRADUCCIÓN " size="30" type="text" name="trad"><br>
<input title="CÓDIGO " size="30" type="text" name="password"><br>
Gracias por colaborar <input title=" ENVIAR " type="submit" value="•">
</form>
</center>
</body>
</html>
<?php }
Just make sure that you call session_start() before any output (in your case the HTML document).
Hope this help.
I am working on a school project and can't get registration page done right. It just doesn't insert the data in table.
Here is a screenshot for database and table
I have added the HTML, and after going through all your answers I think I am using outdated videos and study material to learn (PHP, HTML, CSS, Website Security).
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Register</title>
</head>
<body>
<div class="form">
<h2>Registeration</h2>
<form action="" method="post">
Name<input type="text" name="name" placeholder="First & Last name" required><br><br>
Username<input type="text" name="username" placeholder="Username"required><br><br>
Password<input type="password" name="password" placeholder="Keep it Strong"required><br><br>
Confirm Password<input type="password" name="confirm-pass" placeholder="Re-Enter Password"required><br><br>
Email<input type="email" name="email" placeholder="Email"required><br><br>
Phone No.<input type="text" name="phone-no" placeholder="Phone No"required><br><br>
Gender<input type="text" name="gender" placeholder="Male or Female"required><br><br>
State<input type="text" name="state" placeholder="State"required><br><br>
<button type="submit" name="home">Home</button>
<button type="submit" name="sub">Submit</button>
<button type="submit" name="reset">Reset</button>
</form>
</div>
</body>
</html>
<?php
$con=mysqli_connect('localhost','root','123456789','eedb');
if ($con)
{
if (isset($_POST['sub']))
{
$n= $_POST['name'];
$un=$_POST['username'];
$p=$_POST['password'];
$cp=$_POST['confirm-pass'];
$e=$_POST['email'];
$pn=$_POST['phone-no'];
$g=$_POST['gender'];
$s=$_POST['state'];
mysqli_query($con,"SELECT * FROM `register`");
$insert= mysqli_query($con,"INSERT INTO `register`(`name`, `username`, `password`, `confirm-pass`, `email`, `phone-no`, `gender`, `state`) VALUES ('$n','$un','$p','$cp','$e','$pn','$g','$s')");
if ($insert)
{
echo "<center>Data Successfully Submitted</center>";
}
else
{
echo "<center>Data Not Submitted</center>";
}
}
}
else
{
echo "<center>Oh!no there is an error.<br><br>But don't worry we have an army of trained chimpanzies to deal with it.<br><br> <image src='images/chimps.jpg'><br><br>Come Back Soon</center>";
}
if (isset($_POST['home']))
{
header("location:index.php");
}
if (isset($_POST['reset']))
{
header("location:register.php");
}
?>
Since you didn't post your HTML form, I am posting the following answer, which is what your HTML form should (basically) look like, which btw only contains the one example element.
You will need to fill in the rest and follow the same convention.
<form method="post" action="handler.php">
First name:
<input type="text" name="name">
<br>
<input type="submit" name="sub" value="Submit">
</form>
Then escape your values, should there contain any characters that MySQL may complain about, such as apostrophes.
I.e.: Doug's Bar & Grill.
Then:
$n= mysqli_real_escape_string($con, $_POST['name']);
Something you should use or a prepared statement since your code is presently open to an SQL injection.
Ref: How can I prevent SQL injection in PHP?
And do the same for all your other POST arrays.
The name attribute is required for POST arrays when using pure PHP and a post method for the HTML form.
Sidenote: Your entire code is dependant on the following conditional statement
if (isset($_POST['sub'])){...}. So make sure that that form element bears the same name attribute for it.
Check for errors also.
Since this does not help you:
echo "<center>Data Not Submitted</center>";
References:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/function.error-reporting.php
It's unclear as to what you're trying to do with this line:
mysqli_query($con,"SELECT * FROM `register` ");
If the goal is to check if a row exists, then consult one of my answers on Stack:
check if row exists with mysql
Passwords
I also noticed that you may be storing passwords in plain text. This is not recommended.
Use one of the following:
PHP 5.5's password_hash() function.
Compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/
Important sidenote about column length:
If and when you do decide to use password_hash() or the compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/, it is important to note that if your present password column's length is anything lower than 60, it will need to be changed to that (or higher). The manual suggests a length of 255.
You will need to ALTER your column's length and start over with a new hash in order for it to take effect. Otherwise, MySQL will fail silently.
Other links of interest:
CRYPT_BLOWFISH
crypt()
bcrypt()
scrypt()
On OPENWALL
PBKDF2
PBKDF2 on PHP.net
PBKDF2 For PHP
HTML stickler:
The <center> tag is deprecated and has been removed from Web standards.
For more information, visit the following:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/center
you can try this
$insert= mysqli_query($con,"INSERT INTO `register`(`name`, `username`, `password`, `confirm-pass`, `email`, `phone-no`, `gender`, `state`)VALUES ('$n','$un','$p','$cp','$e','$pn','$g','$s')");
you can try to use notepad++ or any other editor (e.g netbeans )that will make the open and closed brackets more obvious .
I am working on my first $_POST form. I have created a simple HTML form and used the post method and my action points to a php document. I want to do some validation with the php to make sure the passwords match and simple things like that. I guess I am not understanding how to make the form work for me because right now when I submit my form, all it does is show my php code on the next page. How do you get the php to actually check the values instead of just displaying the code? Here is what I have for my php file:
<?php
function validatePassword($pwd) {
//create array to store test information
$messages = [];
//test for at least 8 characters
if (strlen($pwd) < 8) {
$messages []= "Your Password Must Contain At Least 8 Characters!<br />";
}
//test for max length
if (strlen($pwd) > 16) {
$messages []= "Your Password is too long!<br />";
}
//test to see if password contains number
if(!preg_match("#[0-9]+#", $pwd)) {
$messages []= "Your Password Must Contain At Least 1 Number! <br />";
}
//test to see if password has capital letter
if(!preg_match("#[A-Z]+#", $pwd)) {
$messages []= "Your Password Must Contain At Least 1 Capital Letter!<br />";
}
//test to see if password has a lowercase letter
if(!preg_match("#[a-z]+#", $pwd)) {
$messages []= "Your Password Must Contain At Least 1 Lowercase Letter!<br />";
}
//test to see if password has special character
if(!preg_match("#[^0-9A-Za-z]#", $pwd)) {
$messages []= "Your Password Must Contain At Least 1 Special Character!<br />";
}
//test to see if password contains a space
if (strpos($pwd, ' ') > 0) {
$messages []= "Your password cannot contain a space!<br />";
}
//password passed all tests
if (empty($messages)) {
return "Password is acceptable<br />";
}
//return the array
return implode("\n", $messages);
}
if ($pass1 != $pass2){
$msg = "Passwords do not match";
}
else{
$msg = "Password confirmed!";
}
validatePassword($pass1);
?>
Form code:
<html>
<head>
<title>PHP Form</title>
</head>
<body>
<form name=newForm method=post action=formProcess.php>
UserName: <input type=text name=userName size=15 maxlength=15><br>
Password: <input type=password name=pass1 size=15><br>
Confirm Password: <input type=password name=pass2 size=15><br>
<p>
I agree to the terms and conditions.<br>
<input type=radio name=terms value=yes> Yes
<input type=radio name=terms value=no> No
<p>
Enter comments here:<br>
<textarea name=comments rows=6 cols=50 wrap=physical></textarea>
<p>
<input type=submit name=submitForm>
<input type=reset name resetForm>
</p>
</form>
</body>
</html>
By the way I know I can put the php in the HTML document, but I really want to attempt to do two seperate files and see how this works. Thanks for any help!
It seems you don't have a web server
Download xampp and place your php file in the htdocs folder of the server, then you should be able to see it on http://localhost
Don't forget to actually start your Apache server and make sure it has a green light and no errors. Usually Skype will block it because it uses its port, so be careful on that.
Ok, first let's make some valid HTML
<html>
<head>
<title>PHP Form</title>
</head>
<body>
<form name="newForm" method="post" action="formProcess.php">UserName:
<input type="text" name="userName" size="15" maxlength="15">
<br>Password:
<input type="password" name="pass1" size="15">
<br>Confirm Password:
<input type="password" name="pass2" size="15">
<br>
<p>I agree to the terms and conditions.
<br>
<input type="radio" name="terms" value="yes">Yes
<input type="radio" name="terms" value="no">No
<p>Enter comments here:
<br>
<textarea name="comments" rows="6" cols="50" wrap="physical"></textarea>
<p>
<input type="submit" name="submitForm">
<input type="reset" name="resetForm">
</p>
</form>
</body>
</html>
Then in your formProcess.php file, delete everything and try something like
<?php
echo $_POST["userName"];
?>
If this doesn't print the value you submitted in your username field, then there is a problem with your server.
In order to run PHP pages you need to first install it with a web server.
If you're using windows you can try WAMP which bundles PHP with Apache and MySQL:
http://www.wampserver.com/en/
For Linux:
https://www.digitalocean.com/community/tutorials/how-to-install-linux-apache-mysql-php-lamp-stack-on-ubuntu
For MAC:
https://www.mamp.info/en/
In PHP there are two type validation such javascript validation (Client side validation) and another is Php Validation such as (Server side Validation).
1- In java Script validation done on Client Machine.
2- In Server Side (PHP validation) Done On server.
I'm creating a SQL Injection demo as a project for my class. I've created a login page but i cant seem to be able to inject it. Here is what I have written for the page. I have tried blind SQLi creating multiple clauses withing the username field. The only other thing I can think of is to use subqueries or to change my code to make it easier.
EDIT* Trying to Inject the username field *
<?php // Check to see if there was a request method that is a post type
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
// Check to see if username field is null
if (!empty($_POST['username'])) {
// Connect to the server using credentials
$con = mysql_connect('localhost','root','sqlcool1');
// If the connection was not successful
if (!$con){
echo 'OUCH';
die('Could not connect: '.mysql_error());
}
// Select the correct database from the server
$db = mysql_select_db('injectme',$con);
// Pass a sql query through the table to pull the user field that was entered in the form
// Return the results in an array
$sql = mysql_query('SELECT * FROM user WHERE username = "' . $_POST['username'] . '"');
$row = mysql_fetch_row($sql);
// compare $row["password"] to $_post["password"]
// if they match it's good: log them in
// if not, they're beat: don't log them in
if ($_POST["username"] == $row[1] && $_POST["password"] == $row[2]) {
// do something to let them know that it worked
echo('<html>
<head>
<meta http-equiv="refresh" content="3; url=search.php">
</head>
<body>
<p style="color:green">logged in</p>
</body>
</html>');
} else {
// do something to let them know it didn't work
echo('<p style="color: red">Invalid username or password.</p>');
echo('<form name="login" action="login.php" method="POST">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="submit" name="submit_button" value="Submit">
<button type="submit" formaction="register.php">Register</button>
</form>');
}
//Close the connected session with the server
mysql_close($con);
} else {
// Repost Form
echo ('<p style="color: red"> No username / password provided.</p>');
echo('<form name="login" action="login.php" method="POST">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="submit" name="submit_button" value="Submit">
<button type="submit" formaction="register.php">Register</button>
</form>');
}
}
else
{
echo('<form name="login" action="login.php" method="POST">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="submit" name="submit_button" value="Submit">
<button type="submit" formaction="register.php">Register</button>
</form>');
}
?>
The code you have posted is entirely vulnerable and can be used to view the content of the entire database. One way to exploit it is with time based attack where you create an artificially long response time if a condition is true.
Consider the following username :
" UNION SELECT (WHEN "A" = (SUBSTR(password, 1, 1)) THEN SLEEP(5) ELSE 1 END) AS username, 1 as password FROM user LIMIT 0, 1 --
If the response is longer than 5 seconds, you can know the value of the first character is "A" otherwise just test for an other character. After that you just have to repeat the same pattern for other position in the string until you have found all characters of the password. After that, you can just directly use the admin password. Since it requires a lot of queries those type of attack are often scripted.
If you want to read more about it, it's called Blind SQL Injection.
To successfully exploit this vulnerability, you need to be able to inject some code such that the resulting SQL statement will return something that will pass the later test:
$_POST["username"] == $row[1] && $_POST["password"] == $row[2]
So the second column needs to be equal to the submitted username and the third row needs to be equal to the submitted password.
Now as the injection happens with the submitted username, you have a problem.
Because you cannot supply a username that fulfills both the inject some data into the result set aspect and the inject a value for the username that is identical to the injected code that injects a value for the username aspect.
The former is quite easy (assuming three columns in user):
username := '" UNION SELECT 1, "admin", "'
password := ''
This results in:
SELECT * FROM user WHERE username = "" UNION SELECT 1, "admin", ""
However, the $_POST["username"] == $row[1] part remains unresolvable as you would need to make the second SELECT return the submitted username as username column value. And that’s just not possible.
Now if you just remove the $_POST["username"] == $row[1] it works fine.
It depends on what you are trying to inject. If you are trying to inject a second query, this is not possible - the mysql_query function does not support multiple queries. From the docs:
mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified link_identifier.
Of course, it is still vulnerable to additional WHERE clause injections.
This question already has answers here:
Is it possible to decrypt MD5 hashes?
(24 answers)
Closed 9 years ago.
How to fetch md5 password from database.
i am making a login form>
i want,when the user is going to login.if the username and password text field is matched with database than use will login.
database..
in database,i store the password with md5().
now how to fetch the password from database.and how to make validation with this.
thanks all
<h1>Login Here</h1>
<form name="f1" action="login.php" method="post">
<table border="1">
<tr><td>username</td><td><input type="text" name="t1"></td></tr>
<tr><td>password</td><td><input type="password" name="t2"></td></tr>
<tr><td><input type="submit" value="login"></td></tr>
</table>
</form>
login.php
<?php
include "db.php";
$user=$_POST['t1'];
$pass=$_POST['t2'];
$result=mysql_query("select * from core where username='$user'")or die(mysql_error());
$row=mysql_fetch_row($result);
?>
<h1>Welcome Mr. <?php echo $user;?></h1>
<table border="1">
<tr><td>Your User-Id :- </td><td><?php echo $row[0];?></td></tr>
<tr><td>Your Username: </td><td><?php echo $row[1];?></td></tr>
<tr><td>your md5 Password: </td><td><?php echo $row[2];?></td></tr>
<tr><td>your Email Id: </td><td><?php echo $row[3];?></td></tr>
</table>
Dont try to decode the password from database and check it with that of user entered input pasword.Instead of that try encoding the user entered password as md5 and check it with that it the database.
There is no way to decrypt MD5. Well, there is, but no reasonable way
to do it. That's kind of the point.
To check if someone is entering the correct password, you need to MD5 whatever the user entered, and see if it matches what you have in the database.
For more you can check in this answer.
So what you can do is like this
if(isset($_POST['t2']) && trim($_POST['t2']) != ''){
$pass = md5(trim($_POST['t2']));
//Do a select query for fetching with the username and $pass and do the rest
}