How to hash a password
UPDATE: THIS ANSWER IS SERIOUSLY OUTDATED. Please use the recommendations from the https://stackoverflow.com/a/10402129/251311 instead.
You can either use
var md5 = new MD5CryptoServiceProvider();
var md5data = md5.ComputeHash(data);
or
var sha1 = new SHA1CryptoServiceProvider();
var sha1data = sha1.ComputeHash(data);
To get data
as byte array you could use
var data = Encoding.ASCII.GetBytes(password);
and to get back string from md5data
or sha1data
var hashedPassword = ASCIIEncoding.GetString(md5data);
How to use PHP's password_hash to hash and verify passwords
Using password_hash
is the recommended way to store passwords. Don't separate them to DB and files.
Let's say we have the following input:
$password = $_POST['password'];
You first hash the password by doing this:
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
Then see the output:
var_dump($hashed_password);
As you can see it's hashed. (I assume you did those steps).
Now you store this hashed password in your database, ensuring your password column is large enough to hold the hashed value (at least 60 characters or longer). When a user asks to log them in, you check the password input with this hash value in the database, by doing this:
// Query the database for username and password
// ...
if(password_verify($password, $hashed_password)) {
// If the password inputs matched the hashed password in the database
// Do something, you know... log them in.
}
// Else, Redirect them back to the login page.
Official Reference
How to create a laravel hashed password
Hashing A Password Using Bcrypt in Laravel
:
$password = Hash::make('yourpassword');
This will create a hashed password. You may use it in your controller or even in a model, for example, if a user submits a password using a form to your controller using POST
method then you may hash it using something like this:
$password = Input::get('passwordformfield'); // password is form field
$hashed = Hash::make($password);
Here, $hashed
will contain the hashed password. Basically, you'll do it when creating/registering a new user, so, for example, if a user submits details such as, name
, email
, username
and password
etc using a form, then before you insert the data into database, you'll hash the password after validating the data. For more information, read the documentation.
Update:
$password = 'JohnDoe';
$hashedPassword = Hash::make($password);
echo $hashedPassword; // $2y$10$jSAr/RwmjhwioDlJErOk9OQEO7huLz9O6Iuf/udyGbHPiTNuB3Iuy
So, you'll insert the $hashedPassword
into database. Hope, it's clear now and if still you are confused then i suggest you to read some tutorials, watch some screen casts on laracasts.com and tutsplus.com and also read a book on Laravel
, this is a free ebook, you may download it.
Update: Since OP
wants to manually encrypt password using Laravel Hash
without any class or form so this is an alternative way using artisan tinker
from command prompt:
- Go to your command prompt/terminal
- Navigate to the
Laravel
installation (your project's root directory) - Use
cd <directory name>
and press enter from command prompt/terminal - Then write
php artisan tinker
and press enter - Then write
echo Hash::make('somestring');
- You'll get a hashed password on the console, copy it and then do whatever you want to do.
Update (Laravel 5.x):
// Also one can use bcrypt
$password = bcrypt('JohnDoe');
How do we hash a put request password?
Solution 1: Easy Way
For your personal solution, without really modifying the code, it works like the following.
// updating a user
router.put('/:id', async (req, res) => {
const {error} = validate(req.body)
if (error) return res.status(400).send(error.details[0].message)
// Why not make the hash function here?
const salt = await bcrypt.genSalt(10)
const newPassword = await bcrypt.hash(req.body.password, salt)
const user = await User.findByIdAndUpdate(req.params.id, {
$set : {
name: req.body.name,
email: req.body.email,
password: newPassword
}
})
if (!user) return res.status(404).send('User with that id does not exist')
res.send(user)
})
You have a mistake in your user.password
call. The findByIdAndUpdate
method does not return an object that you can modify instantly. In above workaround, we simply move the function so that it hashes the new password first before updating your document.
Solution 2: My Own Style
For my personal solution, I'd go like this. Let's say that you have a userModel
that stores the schema of your User
entity. I will add a new middleware that will run every time the password changes.
/** your user schema code. **/
userSchema.pre('save', async function (next) {
// Only run the encryption if password is modified.
if (!this.isModified('password')) {
return next();
}
// Hash the password with BCRYPT Algorithm, with 12 characters of randomly generated salt.
this.password = await bcrypt.hash(this.password, 12);
next();
});
Next, we'll create a new dedicated route in order to handle password changes. I think it's better if we define a new route for it as passwords are sensitive data. Below is pseudocode, don't instantly copy and paste it, it wouldn't work.
const user = await User.findById(...);
user.password = req.body.password;
await user.save({ validateBeforeSave: true });
Remember that save
middleware runs every time after the save
command is run.
Further reading about Mongoose's middlewares here.
Where do I hash the password?
In the view: This is too high up. There will almost certainly be multiple views in your application which do things with passwords (two simple ones: login form and password change form), and having password hashing in the view would lead to duplication.
In the database: Too low down. The database should never see plaintext passwords; doing this could, in some situations, end up sending plaintext passwords over the network, displaying them in error messages, or writing them to database logs. Moreover, most of the hash functions supported by databases are too fast to be secure for password storage.
In the model: Just right. I'd recommend implementing methods on the user object resembling:
$user->setPassword($password) # sets password to specified value
$user->passwordEquals($password) # returns true if value passed in matches the passwordNote that none of these methods ever expose the password, or how it's stored -- that's all an implementation detail of the object.
SQL Server - How to insert a hashed password to a table?
As mentioned, I don't understand the problem here. Just use HASHBYTES
in your parametrised INSERT
:
INSERT INTO dbo.Users (EmailAddress, UserPassword, FirstName, LastName, MobileNumber)
VALUES(@EmailAddress, HASHBYTES('SHA2_256',@Password), @FirstName, @LastName, @MobileNumber);
Side Note: As I mentioned in my other answer, bigint
isn't the right choice for a telephone number. Phone Numbers can start with a 0
and contain other characters from digits. A value like '01234567890'
would be changed to 1234567890
, a number like '+441234567890'
would be changed to 441234567890
, and a number like '(01234) 567890'
would fail to INSERT
completely
Related Topics
How to Get Output from a Command to Appear in a Control on a Form in Real-Time
Conditional Operator Cannot Cast Implicitly
Json.Net Parser *Seems* to Be Double Serializing My Objects
Tips For Optimizing C#/.Net Programs
Dynamic Where Clause (Or) in Linq to Entities
Getting Servicestack to Retain Type Information
Passing Arguments to C# Generic New() of Templated Type
How to Do Constructor Chaining in C#
How to Use Optional Parameters in C#
C# Data Connections Best Practice
Why Is Dictionary Preferred Over Hashtable in C#
Unity: Null While Making New Class Instance
Sharing Sessions Across Applications Using the ASP.NET Session State Service
What Does "Use of Unassigned Local Variable" Mean
Line Delimited Json Serializing and De-Serializing
How to Retrieve Id of Inserted Entity Using Entity Framework