How do I protect my password on the website? - javascript

On the site, the login is made using a code of the type if the entered password matches the variable in which the password is stored, then the person enters the site. How to protect the site from the magic F12 button? I.e. how to make the password impossible to find
out
p.s. I have never done anything like this so the experience is 0.
I wrote the code and don't know how to protect passwords.
function checkUsernamePassword() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username == "admin" && password == "12345") {
window.location = "../index.html";
}
else {
window.location = "invalid-login.html";
}
}

Ordinarily, your approach would be easily bypassed.
However, with the WebCrypto API you can use strong encryption to protect the data that needs to be accessed with a password.
You'd use a salted PBKDF2 to stretch the password into a symmetric encryption key. Then, the data can only be accessed when the correct password is entered.
This approach relies on the password being of sufficient entropy to prevent a brute-force attack.

Related

nodejs - how to compare two hashes password of bcrypt

Hello I need some help with this issue after I search the solution and I have not found yet,
I want to compare 2 hash password with bcrypt of the same password,
how do I do it?
for example:
I have these 2 hash password that came from the same password in bcrypt:
var password = E#Js#07Do=U$
var hash1 = $2a$10$fKAyjaG0pCkisZfRpKsBxursD6QigXQpm1TaPBDZ4KhIZRguYPKHe
var hash2 = $2a$10$mgApOcRIp7RSK3lRIIlQ5e/GjVFbxAFytGAEc0Bo17..r8v2pPR22
// that's not working for me
bcrypt.compare(passwordHash, userPasswordLoginHash, function(err, isMatch) {
if (err) throw err;
if(isMatch){
console.log('correct password!')
}
callback(null, isMatch);
});
how can i compare them, to determine that they came from the same password, by using bcryptjs npm package?
This is impossible by design - as a core security property of true password hashing.
If you could compare two password hashes without knowing the original password, then if an attacker cracked one password on the system, they would instantly know the passwords of all users who are using that password, without any additional work. It should be immediately obvious why this would be a bad thing.
For example, if passwords were stored using a hash inappropriate for password storage (such as MD5), then if 50 users had a password of 'password', then all of their hashed passwords would have the identical MD5 hash ('5f4dcc3b5aa765d61d8327deb882cf99'), and cracking one of them would reveal the password of all 50 users.
You can't do that with a modern password hash like bcrypt. The only way to "compare" two modern password hashes is to know the plaintext in advance, and then apply the algorithm using the salt in each hash. And even if two users have the same password, the attacker has to perform the same expensive computation to crack each of them independently, because the unique salts make each hash unique.
More generally - and this may sound a bit bold - but there is no legitimate use case for any system or administrator to ever compare two different users' passwords. User passwords should be 100% independent and 100% opaque to the system once stored. If a system or business case requires this kind of comparison, it should be redesigned to eliminate that requirement.
"With bcrypt lib you compare plain text password to the one hashed using the same lib."
The problem is with a micro services architecture, that is very insecure. If I have a front end passing an unhashed password to the backend, the unhashed password is getting logged (possibly in multiple places) before it gets compared against the hash in the DB on the system backend.
With bcrypt lib you compare plain text password to the one hashed using the same lib.
Say you hashed a password
const myPlaintextPassword = 'E#Js#07Do=U$'
bcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash) {
// Store hash in your password DB.
// example output, taking your hash
// hash = $2a$10$fKAyjaG0pCkisZfRpKsBxursD6QigXQpm1TaPBDZ4KhIZRguYPKHe
});
You compare like:
// db query, get hashed password, found hash
// hash = $2a$10$fKAyjaG0pCkisZfRpKsBxursD6QigXQpm1TaPBDZ4KhIZRguYPKHe
// User input again:
const myPlaintextPassword = 'E#Js#07Do=U$'
bcrypt.compare(myPlaintextPassword, hash, function(err, res) {
// res is true as the original password is the same
// res == true
});
For a bit extra security you can encrypt the password in the front-end and decrypt and compare in the back-end

How to send email using Javascript in a simplest way?

I'm doing the final project in my XML & JavaScript course and I'm having trouble with sending email via JavaScript.
I found this page: http://smtpjs.com/. But it requires SMTP credentials, I don't know what SMTP credentials is.
Who has used smtpjs.com or who has the solution please help me.
P/s: Do I need to upload my code to a host to send email. I always open html file from my computer, I wonder whether it will be able to send email or not.
First of all, I don't think you should run your code from the html file. You run it from a server to properly communicate with smtp.js
You can try this:
$('#form-submit').click(function () {
submitForm();
});
function submitForm() {
// Initiate Variables With Form Content
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
if (name == "") {
alert('Invalid Name');
return;
}
if (message == "") {
alert('Message cannot be empty');
return;
}
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (!emailReg.test(email)) {
alert('Invalid Email');
return;
}
Email.send("from#email.com",
"to#email.com",
"Message from " + name + " " + email,
message,
{
token: "63cb3a19-2684-44fa-b76f-debf422d8b00",
callback: function done(message) { alert("sent") }
});
}
I also used smtpjs and sendgrid.
I hope this helps.
If you want to send an email in javascript, you should turn on allow secure app access in Gmail.
Google will not let you send emails if you do not turn on allow the less secure app in Gmail.
Here is the link to:
Turn On Allow Secure App Access
Please note if you turn on the function in google, it is easy for attackers to find information about your Gmail account.
It is recommended to create an account just for development.
SMTP is the server that handles mails. Here is google's: 'smtp.gmail.com'.
You can directly send an e-mail from javascript. I suggest you go for JSON.

How do I encrypt a variable in javascript?

I have been searching for ages and couldn't find a way to encrypt my javascript variable, because its used for a password:
function lg() {
var input = document.getElementById("values").value;
if (input == pass) {
$("nil").replaceWith($("<success>" + "Success!" + "</success>"));
sleep(4000);
sleep(2000);
window.location.replace("http://google.com");
}
else if (input == "") {
$("nil").replaceWith($("<error>" + "Error: No input detected!" + "</error>"));
}
else {
$("nil").replaceWith($("<error>" + "Incorrect Password!" + "</error>"));
}
}
var pass="test3r"; // The one I need to encrypt
I don't think you would need my html or css as its just my javascript variable I need to encrypt. The variable I need to encrypt is my var pass one.
If your javascript is running on client side so it's not best decision to hold password in js code. And any user can just skip password check by editing code.
But if you really need this, only option I see is to use hash of password and some js library to create exact hash of user input.
For example if you will you md5 hash function (not really strong one, but there are lost of implementations in js) your password hash will look like a50bdfb74649a14c1f86b6d012f2caad
And password check will looks like if (md5(input) == pass) { ...
}
You should read about hash functions and use "salt" when hashing password to make decoding your password harder.

Get the actual text of an 'sha512' encrypted text

So I'm developing a website using php, mysql and javascript, and also 'sha512' to encrypt passwords of members using the code :
$password = filter_input(INPUT_POST, 'p', FILTER_SANITIZE_STRING);
$random_salt = hash('sha512', uniqid(mt_rand(1, mt_getrandmax()), true));
$password = hash('sha512', $password . $random_salt);
the p value is comming from :
function formhash(form) {
var password = randomString();
var p = document.createElement("input");
form.appendChild(p);
p.name = "p";
p.type = "hidden";
p.value = hex_sha512(password.value);
password.value = "";
form.submit();
}
function randomString() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 9; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
My idea here is to reset user password by entering their email and generate random 8 characters then send it directly to their email.
The problem I'm facing now is how to get the actual password (not encrypted) that has been generated so it can be automatically sent to the email of the member who requested to reset their password?
Good question.
First, you should never send users their passwords in plaintext. It's considered a bad security practice for a few reasons. If anyone gets access to the email, then they have the password and can hijack the user account. Second, hashing is a one-way form of encryption where you turn the password into gibberish. The big value in hashing is that the same password will always be turned into the same gibberish-- everytime. This means you can do password matching without ever storing the raw password. The reason you're supposed to hash a password and not do 2-way encryption like AES-256, is that 2-way encryption requires the creation, management, and securing of encryption keys which can be hard. Hashing is just easier and more secure for the vast majority of developers.
So how should you implement password reset if you can't send the raw password?
You send the user an email with a link to a secure reset page AND a one-time use reset token that expires within a certain window. This way, if someone get's access to the email then the window of risk is limited to the short window.
There are a variety of ways to build this yourself but an easy approach to getting a one-time use token you don't have to store or manage is to offload user management to a microservice like Stormpath where it takes care of all the user management for you-- password reset, password storage, user profiles, authentication, etc.
For password reset here's what it would look like:
User initiates password reset work on a web page
You make API call to stormpath with user's email address or username
Stormpath sends out reset email to user (your "from" address, custom HTML, etc) with a link + token. The reset token that is unique, one-time use, and expires if not used within 24 hours
User clicks on the link and lands on the reset page
You pull the token from the URL and check Stormpath for token verification
User submits new password
Stormpath sends out reset success message (your "from" address, custom HTML, etc)
You can build your own UIs in this flow so the user never knows Stormpath exists.
Now, you don't have to manage, store, or secure any passwords or reset tokens in your database.
Here's are some links to the community-managed PHP SDK.
http://docs.stormpath.com/php/quickstart/
http://docs.stormpath.com/php/product-guide/
Full Disclosure - I work at Stormpath
and also 'sha512' to encrypt passwords
You're not encrypting them, you're hashing them. A hash is a one-way function. You can't take the result of a hash function and get the original. There are many possible original chunks of data that can result in the same hash.
The whole point of hashing in this context is to be able to check passwords without ever actually storing the user's password. You shouldn't send the user their password in e-mail, as e-mail is sent over the internet unencrypted. If you must have the original pre-hashed data for some reason, you must store it before you hash it.

Nodejs bcrypt library

I use the nodejs bcrypt library for better password protection.
I am not sure i understand exactly how to use it, but i got this so far:
//A module containing this login function:
login: function(credentials,req,res) {
//"credentials" is containing email and password from login form
var query = 'SELECT password, email FROM users WHERE email = ? LIMIT 1';
client.query(query,[credentials.email], function(err, results) {
if (results[0]) {
//Compare passwords
if (bcrypt.compareSync(credentials.password, results[0].password)) {
//Set session data and redirect to restricted area
}
}
});
}
I removed all the error handling here in the example so that its easier to read the code.
1.This works and i am able to login and set the session. But is this all there is to it? Am i missing something?
2.Looks like the salt is prepended to the password when generating hash. Dont I have to save the salt in db?
Any help appreciated
Yes, this is all there is to it! The salt you generate when encrypting the password originally is used to prevent against rainbow table attacks; you do not need to persist it.

Categories