How to decrypt a password from database in php? - php

I am creating a edit information page, but when i call out the data for password, it is encrypted. Is there a way i could decrypt it?
this is my codes,
<?php
require 'dbfunction.php';
$con = getDbConnect();
if (mysqli_connect_errno($con)) {
"Failed to connect to MySQL: " . mysqli_connect_error();
} else {
$result = mysqli_query($con, "SELECT * FROM admininfo where name = xyz");
while ($admininfo = mysqli_fetch_array($result)) {
?>
<div class="container">
<div class="row">
<center>
<h2>Edit Info Administrator</h2>
</center>
<form>
<div class="form-group">
<label class="col-sm-2 control-label">Name</label>
<div class="col-md-10">
<input type="text" class="form-control" value="<?php echo $admininfo['name']; ?>" name="name">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Password</label>
<div class="col-md-10">
<input type="password" class="form-control" placeholder="<?php echo $admininfo['password']; ?>" name="password">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Comfirm Password</label>
<div class="col-md-10">
<input type="password" class="form-control" placeholder="Confirm Password" name="confirmpassword">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<input type="submit" value="edit account" class="btn btn-primary">
</div>
</div>
</form>
</div>
</div>
<?php } mysqli_close($con); } ?>
Currently the name is appearing, only the password is encrypted.

There is no way to tell, from the code you've provided, how the password is encrypted.
If it is done properly, then the password will be stored using a salt and a hashing algorithm and not any kind of reversible encryption. In that case, the answer will be "no".
You should never need to find out what a password is, only set a new one or compare a submitted one to the existing one. The latter case is handled by running the submitted password through the same hashing algorithm and comparing the two hashes.
Your admin probably shouldn't be setting a new password directly either, they should have access to a function that emails the user a one use only token that they can use to set a new password themselves.

This is a bad idea. Currently, you're showing $admininfo['password'] as a placeholder. This means its characters will be actually visible on the screen, even if your input is of type password. Anyone looking over your shoulder will be able to see it. Don't do this.
Passwords should be stored in the database only hashed and salted. There is a way to check whether a certain plaintext is the original password, but there is no way to decrypt the hash (other than brute force). This is done like this for obvious security reasons.
Have a look at password_hash() and password_verify().

Related

How to avoid asking the user to refill all form fields when one field has an error

New to php, would appreciate your help with this:
I made a signup form script to validate the user's input via multiple error handlers. (check valid email, pwd and pwd re-entry match etc).
In case the user filled all fields but one had an error (failed to pass the error handler), i wanted to send back the other fields to the same form so the user doesn't have to refill'm all over again. So if the passwords dint match, i wanted to reload the same page but with the other filed filled.
i can see the information in the url of the page but not in the form fields.
below my form HTML
<div class="register-content">
<form action="includes/signup.inc.php" method="POST" class="margin-bottom-0">
<label class="control-label">Name <span class="text-danger">*</span></label>
<div class="row row-space-10">
<div class="col-md-6 m-b-15">
<input type="text" name="uFirst" class="form-control" placeholder="First name" required />
</div>
<div class="col-md-6 m-b-15">
<input type="text" name="uLast" class="form-control" placeholder="Last name" required />
</div>
</div>
<label class="control-label">Username <span class="text-danger">*</span></label>
<div class="row m-b-15">
<div class="col-md-12">
<input type="text" name="uName" class="form-control" placeholder="Username" required />
</div>
</div>
<label class="control-label">Email <span class="text-danger">*</span></label>
<div class="row m-b-15">
<div class="col-md-12">
<input type="text" name="mail" class="form-control" placeholder="Email address" required />
</div>
</div>
<label class="control-label">Password <span class="text-danger">*</span></label>
<div class="row m-b-15">
<div class="col-md-12">
<input type="password" name="pwd" class="form-control" placeholder="Password" required />
</div>
</div>
<label class="control-label">Re-enter Password <span class="text-danger">*</span></label>
<div class="row m-b-15">
<div class="col-md-12">
<input type="password" name="pwd-repeat" class="form-control" placeholder="Re-enter Password" required />
</div>
</div>
Below my php code
<?php if(isset($_POST['signup-submit'])) {
require 'dbh.inc.php';
$firstName=$_POST['uFirst'];
$lastName=$_POST['uLast'];
$userName=$_POST['uName'];
$email=$_POST['mail'];
$password=$_POST['pwd'];
$passwordRepeat=$_POST['pwd-repeat'];
if (!filter_var($email, FILTER_VALIDATE_EMAIL) && !preg_match("/^[a-zA-Z0-9]*$/", $username)) {
header("location: ../signup.php?error=invalidemail&uid&uFirst=".$firstName."&uLast=".$lastName);
exit();
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("location: ../signup.php?error=invalidemail&uFirst=".$firstName."&uLast=".$lastName."&uName=".$userName);
exit();
} else if (!preg_match("/^[a-zA-Z0-9]*$/", $username)) {
header("location: ../signup.php?error=invaliduid&uFirst=".$firstName."&uLast=".$lastName."&mail=".$email);
exit();
} else if ($password !== $passwordRepeat) {
header("location: ../signup.php?error=passwordnotmatching&uFirst=".$firstName."&uLast=".$lastName."&uName=".$userName."&mail=".$email);
exit();
?>
There are several ways to address this. Ultimately, there are two high-level options:
Pass the valid values back into the new form
Never remove the valid values(i.e. JavaScript + AJAX)
With your current setup, (1) would be simpler. To work with your current design, you would need to store the values somewhere to pass back to the form to render. The simplest would be to add them to the URL parameters(query string), but other options include cookies or session storage.
The simplest option would be to combine your form and validation into a single endpoint rather than separating them. That way, you already have the post data when rendering the form with the error messages.
Once you have the values, you can simply insert them into the form HTML with the value attribute(be sure to HTML encode(htmlentities) any user input values to avoid XSS vulnerabilities).
For example:
<input type="text" name="uFirst" class="form-control" placeholder="First name" value="<?= htmlentities($firstName) ?>" required />
I just noticed(from one of the comments) that you are already passing your valid values in the query string with your existing redirect. In that case, you can simply do something like this:
<input type="text" name="uFirst" class="form-control" placeholder="First name" value="<?= htmlentities($_GET["uFirst"]??"") ?>" required />
Encoding the values is very important. Not properly encoding values, especially from user input, can allow malicious users to craft values that break out of your HTML and alter the page, a vulnerability known as Cross-Site Scripting(or XSS, for short).

If password in textbox doesn't match databases', stop FORM from submitting

In the update password form, if the current password is not same as what is there in the database how should I stop the form from submitting?
Presently, I have a form wherein using AJAX I am checking if the password in the textbox is same as that in the database and if not, it displays a message that password is incorrect but when I submit the form with a new password, the password gets updated.
I want that if password in textbox is not the same as is present in the database, execution should stop until correct password is not entered.
FORM
<h5>Update Password</h5>
</div>
<div class="widget-content nopadding">
<form class="form-horizontal" method="post" action="#" name="password_validate" id="password_validate" novalidate="novalidate">
<div class="control-group">
<label class="control-label">Current Password</label>
<div class="controls">
<input type="password" name="current_pwd" id="current_pwd" />
<span id="chk_pwd"></span>
</div>
</div>
<div class="control-group">
<label class="control-label">New Password</label>
<div class="controls">
<input type="password" name="new_pwd" id="new_pwd" />
</div>
</div>
<div class="control-group">
<label class="control-label">Confirm Password</label>
<div class="controls">
<input type="password" name="confirm_pwd" id="confirm_pwd" />
<span id="chk_confirm_pwd"></span>
</div>
</div>
<div class="form-actions">
<input type="submit" name="submit" value="Validate" class="btn btn-success">
</div>
</form>
JQUERY
$(document).ready(function(){
$('#new_pwd').click(function(){
var current_pwd=$('#current_pwd').val();
$.ajax({
type:'get',
url:'admin_profile_settings_back.php',
data:{current_pwd:current_pwd},
//dataType:"html",
success:function(resp){
$("#chk_pwd").html(resp).show().fadeOut(3000);
}
})
})
})
PHP Backend for AJAX
<?php
session_start();
include "../includes/config.php";
$current_pwd=$_GET['current_pwd'];
$aid=$_SESSION['aid'];
$r=$mysqli->query("SELECT * FROM admin WHERE aid='$aid' ");
$row=$r->fetch_assoc();
if($current_pwd==$row['password'])
{
echo "Password Is Correct";
}
else
{
echo "Password Is Incorrect";
}
You should include a where clause to check for the current password.
You should hash + salt your password
This example does not have any input checks, you should always verify user input, ALWAYS.
You should use the PDO library and perform prepare statements, is more secure than mysqli, also you can mysqli_real_escape_string() at minimum
<?php
session_start();
include "../includes/config.php";
$current_pwd=$_GET['current_pwd'];
$aid=$_SESSION['aid'];
$current_pwd = $mysqli->real_escape_string($current_pwd);
$r=$mysqli->query("SELECT * FROM admin WHERE aid='$aid' and password='$current_pwd' ");
$row=$r->fetch_assoc();
if($current_pwd==$row['password'])
{
echo "Password Is Correct";
}
else
{
echo "Password Is Incorrect";
}

Updating form class based on input using database lookup

I have no clue where to start with this. Basically, I want the class of a input to change to has-success when a username that is in a database table called Username is equal to the string that the user has written. The current code for the form is:
<div class='container col-md-3 rounded p-5 mt-5 border'>
<form action="Authentication.php" method ="post">
<h3 class='text-center'>Please Login</h3>
<h5 class='pt-3'>Enter Username and Password</h5>
<div class="form-group mb-0">
<input class='form-control float-left mt-3 mb-1' placeholder="Username" type="text" name="username">
<br>
<input class='form-control float-left mb-3' placeholder="Password" type="password" name="password">
<br>
</div>
<div class="text-center">
<input type="submit" class='btn btn-primary btn-sx' value="Login">
</div>
</form>
</div>
So whenever anyone types in the field with placeholder="username" it needs to check whether that string matches with any in the column Username in the table Students and if it does update the class to success.
Thanks so much for the help,
Toby
If the code above is in Authentication.php witch is called by the form, then where you check if $_POST has been submitted, initialize a $extraClass = '';
If (your_condition is true) $extraClass = 'success';
and down there in the form, add an
This way it will keep it empty if the condition si not met.

what is wrong with my php login code? Beyond Security Support keeps sending me warnings

I keep getting emails from Beyond Security Support website telling me of all my site security issues. First on the list is the word 'username' in my register.php script. I can post the result of that error if needed. I would at some point like to change it to secure login using https instead of http but for now i just want to solve this issue. It tells me to use prepared statments which it already does as you can see from the code. It would be nice to make it secure from sql injection and made rather simple. this is the username section of the code in php.
if(isset($_POST['submit'])){
//very basic validation
if (!preg_match("/^[a-zA-Z0-9_-]*$/",$_POST['username'])) {
$error[] = 'Usernames can only be numbers, letters, and characters _ -';
}
if(strlen($_POST['username']) < 3){
$error[] = 'Username is too short,3 chars min.';
} elseif (strlen($_POST['username']) > 25){
$error[] = 'Username is too long, 25 chars max.';
}
else
{
$stmt = $db->prepare('SELECT username FROM members WHERE username = :username');
$stmt->execute(array(':username' => $_POST['username']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if(!empty($row['username'])){
$error[] = 'Username provided is already in use.';
}
}
and this the login form below
<form role="form" method="post" action="" autocomplete="off">
<h2>Please Sign Up</h2>
<p>Already a member? <a href='/login.php'>Login</a></p>
<hr>
<?php
//check for any errors
if(isset($error)){
foreach($error as $error){
echo '<p class="bg-danger">'.$error.'</p>';
}
}
//if action is joined show sucess
if(isset($_GET['action']) && $_GET['action'] == 'joined'){
echo "<h2 class='bg-success'>Registration successful, please check your email to activate your account.<br />Do not forget to check in your junk mail!.</h2>";
}
?>
<div class="form-group">
<input type="text" name="username" id="username" class="form-control input-lg" placeholder="User Name" value="<?php if(isset($error)){ echo $_POST['username']; } ?>" tabindex="1">
</div>
<div class="form-group">
<input type="email" name="email" id="email" class="form-control input-lg" placeholder="Email Address" value="<?php if(isset($error)){ echo $_POST['email']; } ?>" tabindex="2">
</div>
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<input type="password" name="password" id="password" class="form-control input-lg" placeholder="Password" tabindex="3">
</div>
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<input type="password" name="passwordConfirm" id="passwordConfirm" class="form-control input-lg" placeholder="Confirm Password" tabindex="4">
</div>
</div>
</div>
<div class="form-group">
<input type="text" name="question" id="question" class="form-control input-lg" placeholder="Fill in the missing word. A bird likes to ???? loudly!" value="<?php if(isset($error)){ echo $_POST['question']; } ?>" tabindex="5">
</div>
<div class="row">
<div class="col-xs-6 col-md-6"><input type="submit" name="submit" value="Register" class="btn btn-primary btn-block btn-lg" tabindex="6"></div>
</div>
</form>
I wasnt sure if the whole form code was needed but thought i'd post it all 'just in case'. this is the report they sent me below.
We discovered vulnerabilities in the scripts listed below. Next to each script, there is a description of the type of attack that is possible, and the way to recreate the attack. If the attack is a simple HTTP GET request, you can usually paste it into your browser to see how it works. If it's a POST attack, the parameters for the POST request will be listed in square parenthesis.
Cross Site Scripting
URL: http://www.finchkeeper.com/register.php
Affected Parameter: username
Vector Used: ">alert('foo');
Pattern found: ">alert('foo');
Complete Attack: http://www.finchkeeper.com/register.php [username=">alert('foo'); &email= &password= &passwordConfirm= &question= &submit=Register]
I think the problem is that you are not sanitizing the POST variables when an error occurs. When an error does occur you are echoing the POST variables back to the user.
Try sanitizing the POST array.
what is a good method to sanitize the whole $_POST array in php?
It's because you're echo'ing the raw $_POST['username'] back into the form's <input value=""> when there's an error, without escaping any HTML entities.
So when they submit the form with the username ">alert('foo');, the string alert('foo'); is written back to the page, because the "> part closes the <input> element. They see that as a cross-site scripting vulnerability.
When you echo back the username into the value, you should escape it. Something like this should do:
value="<?php if(isset($error)){ echo htmlspecialchars($_POST['username']); } ?>"
This will break the username if it actually contains HTML-entities, but given the regular expression you use for username validation, you don't want to allow those anyway.

Bootstrap HTML + MySQL PHP Form Security

I've made a html form using Bootstrap. I've used "required" to ensure data is populated in certain fields for the form to be submitted. This form goes to a php script that opens a database connection, inputs the values as per form submitted, directs to a thank you page and closes the connection.
Its my first hand coded form and my concern is security. How do I keep hackers/spammers at bay?
Can you point out, please, issues with my code so I can address them before I put this live. Please be gentle, Im a newbie with about 3 months of coding experience.
Please note the original form actually has 9 fields but I've omitted it presuming those details wont be necessary for this discussion.
HTML Code
<form class="form-horizontal" method="post" action="vacancy.php">
<div class="form-group">
<label for="company" class="col-sm-3 control-label">Company Name *</label>
<div class="col-sm-6">
<input type="text" name="company" class="form-control" placeholder="Enter Company Name" required />
</div>
</div>
<div class="form-group">
<label for="contactperson" class="col-sm-3 control-label">Contact Person *</label>
<div class="col-sm-6">
<input type="text" name="contactperson" class="form-control" placeholder="Enter Full Name" required />
</div>
</div>
<div class="form-group">
<label for="designation" class="col-sm-3 control-label">Designation *</label>
<div class="col-sm-6">
<input type="text" name="designation" class="form-control" placeholder="Enter Designation" required />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-6">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Clear</button>
</div>
</div>
</form>
PHP Code
<?php
$con=mysqli_connect("localhost","db2u","password","db2");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO vacancy (Company, ContactPerson, Designation)
VALUES
('$_POST[company]','$_POST[contactperson]','$_POST[designation]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
header("Location: thankyou.html");
mysqli_close($con);
?>
EDIT : So it seems I need validation. Im looking at jqBootstrapValidation. Even considering htmlspecialchars (which ever is easier). I believe both would do an equally good job right? PDO is a bit too much for me at the moment.
Your code could be compromised by SQL injection http://en.wikipedia.org/wiki/SQL_injection.
Try use htmlspecialchars or better use PDO instead of OLD and DANGEROUS mysql_* functions.
You have not validated any field in your php code,
you should put validation in php file too, any user can remove "required" from input and can post the data.
Never trust the user input. You should escape the strings with mysqli_real_escape_string() function.
http://www.php.net/manual/en/mysqli.real-escape-string.php
$company = mysqli_real_escape_string($_POST[company]);
$contactperson = mysqli_real_escape_string($_POST[contactperson]);
$designation = mysqli_real_escape_string($_POST[designation]);
$sql="INSERT INTO vacancy (Company, ContactPerson, Designation) VALUES ('$company','$contactperson','$designation')";

Categories