Compare if password is correct

Asked

Viewed 183 times

3

How to create a simple Javascript that only asks the user to enter the password 1234 to appear the message password released, if it misses 3 times appear blocked account.

My code so far:

var senha; 
var senha=1234;
senha=parseFloat(prompt("Entre com sua senha: ")); 

if(senha=senha==1234){ 
   document.write("Acesso Liberado"); 
}
  • This is not the correct way to release access, if the user sees the source code will surely see the password

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site

4 answers

2

It doesn’t make much sense to do it in real code because it doesn’t give any security but it’s very simple to do this:

if (prompt("Entre com sua senha: ") == "1234") document.write("Acesso Liberado");

A password is something descriptive and therefore should be a text and not a number, it makes no sense to turn it into a number. All you need to do is compare, you don’t need to assign anything. You don’t even need a variable in this case. And even if you needed to, it doesn’t make sense to create in the way you created it. Try to simplify your code. And don’t use anything you don’t know why you’re using it. In this case you used 6 things needlessly.

To lock the account when it misses 3 times:

function validaSenha() {
    var erros = 0;
    while (true) {
        if (prompt("Entre com sua senha: ") == "1234") {
            document.write("Acesso Liberado");
            break;
        } else if (++erros == 3) {
            document.write("Conta bloqueada");
            return;
        } 
    }
    //aqui faz algo para o caso da liberação
}
validaSenha();

I put in the Github for future reference.

  • It’s just a class exercise......

1

Like the @Maniero has already mentioned:

It doesn’t make much sense to do it in real code because it doesn’t give any security

But, taking it as an exercise, you can do it like this:

errou = 0;
while (errou <= 3) {
		if (errou == 3) {
    		document.write('Conta bloqueada');
        break;
    } 
    if (prompt('Digite sua senha:') == 1234) {
        document.write('Acesso liberado');
        break;
    } else
        errou++;
}

Respecting the statement:

create a simple javascript that only asks the user to enter the password 1234 to appear the message password released, if it misses 3 times appear blocked account

  • 1

    saved my life thanks!!!!

0

You can do this exercise like this if you want to too:

If password is entered 3 times wrong the message blocked account is displayed, otherwise the message Free access will be shown.

var btn = document.getElementsByTagName("button")[0];
var p = document.getElementsByTagName("p")[0];
var respostas = [];

function obterSenha() {
  var senhas = prompt("Entre com sua senha: ");
  respostas.push(senhas);

  if (senhas == "1234") {
    p.innerHTML = "Acesso Liberado";
    p.style.backgroundColor = "green";
    p.style.color = "white";
    btn.disabled = true;
  } else if (senhas != "1234" && respostas.length == 3) {
    p.innerHTML = "Conta Bloqueada";
    p.style.backgroundColor = "red";
    p.style.color = "white";
    btn.disabled = true;
  }
}
<button onclick="obterSenha()">Senha</button>
<p></p>

-1

Buddy, ideally you work with password encryption, so even we developers, who have access to the source code, couldn’t figure out the password.

One of the safe ways to do this is to use SHA256 encoding, but calm down, it’s very interesting working and it’s nothing out of this world!

It scrambles the password in a way that you can’t decrypt, it’s a one-way encryption, it’s impossible to take the generated hash (so it’s called) and find the original content just with it.

Then you ask, "Why do I want this?" That’s where the interesting part comes in!

You encrypt your password with Sha256 (for example) and it will generate hash (a small text), when the person type the password on the page, we will encrypt the password that the person typed, generating the hash of that password typed, and let’s take this hash and compare it with the hash of the original password, if the 2 hashs are the same it means that the password is the same! And even if you have the hash (which is the case for us developers who know how to access the source code), there is no way to know the password! Even if you put the hash instead of the password, it would re-encrypt the hash and generate a different hash, and when you compare it would not equal your password.

This is basically the method that most secure sites do, maybe they use other methods than Sha256, but the principle is the same, on their server they don’t have their password saved, but their hash, so they keep their privacy, because even if someone has their hash, There’s not much you can do with him. There is also how to generate thousands of possibilities and the hash of each to see if it is equal to your hash, but this is very time consuming, and even with powerful computers can take days or even weeks (if not months or years) until you find your password, but by then the server has blocked access after so many attempts.

I made an example of how to use this in an HTML page, the code is very simple, I commented each line to be very easy to understand, so it’s a little big, I’ll put here:

<!-- Chama a biblioteca Crypto-JS 3.1.2 da Google -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/sha256.js"></script>
<script>
// COMO COLOCAR SENHA
// 
// -Abra este site:
// 		https://www.xorbin.com/tools/sha256-hash-calculator
// -Coloque sua senha dentro da área "Data"
// -Clique em "Calculate SHA256 hash"
// -Copie o "SHA-256 hash"
// -coloque na váriavel "SenhaOriginalCodificada" abaixo
// 
// OBS: A senha atual é "asd", não coloque a senha final aqui como eu fiz
var SenhaOriginalCodificada = "688787d8ff144c502c7f5cffaafe2cc588d86079f9de88304c26b0cb99ce91c6";

//Pergunta a senha
var SenhaDigitada = prompt("Digite a senha");

//Codifica a senha digitada
var SenhaDigitadaCodificada  = CryptoJS.SHA256(SenhaDigitada);

//Se a SenhaDigitadaCodificada for igual a SenhaOriginalCodificada
if(SenhaDigitadaCodificada == SenhaOriginalCodificada)
	
	//Se estiver certa
	{
		//mostra um alerta
		alert("acerto mizeravi");
	}
	
	else
	
	//Se estiver errada
	{
		//mostra um alerta
		alert("errrrrrrroooo, vai pro google vai..");
		//redireciona para outra página
		window.location.href = "http://www.google.com";
	}
</script>


<b>Pagina normal</b>

To put the use of 3 attempts and then wait some time, it is much more complex, then you would have to use those famous cookies(I used the HTML5 version of them, they call localStorage), and save in the browser the blocking information, and do the counting part and the time that one can try again, it gets quite complex, but I did also, it’s basically the same thing as the top code, only with a few additions, here’s:

<!-- Chama a biblioteca Crypto-JS 3.1.2 da Google -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/sha256.js"></script>
<script>
// COMO COLOCAR SENHA
// 
// -Abra este site:
// 		https://www.xorbin.com/tools/sha256-hash-calculator
// -Coloque sua senha dentro da área "Data"
// -Clique em "Calculate SHA256 hash"
// -Copie o "SHA-256 hash"
// -coloque na váriavel "SenhaOriginalCodificada" abaixo
// 
// OBS: A senha atual é "asd", não coloque a senha final aqui como eu fiz
var SenhaOriginalCodificada = "688787d8ff144c502c7f5cffaafe2cc588d86079f9de88304c26b0cb99ce91c6";



/*Modelo de ERROS*/
	//Quantidade de erros permitida
	var QntErros = 3;
	//Se não tem qntErros cria no localStorage
	if (!localStorage.QntErros) {
	  localStorage.QntErros = QntErros;
	}
	//Quantia de horas a bloquear a pessoa depois de consumir todos os erros permitidos
	var HorasPenalidade = 1;
	
	//Se não tem dataPermitida anterior salvas, salva 1 segundo atras no localStorage
	if (!localStorage.dataPermitida) {
	  localStorage.dataPermitida = Date.parse(new Date())-1;
	}
	//Pega a data atual
	var DataAtual = Date.parse(new Date());
	//Pega a dataPermitida no localStorage
	var DataPermitida = parseInt(localStorage.dataPermitida);
/* modelo de ERROS*/



//Pergunta a senha
var SenhaDigitada = "";
if(DataAtual >= DataPermitida){
	SenhaDigitada = prompt("Digite a senha");
}

//Codifica a senha digitada
var SenhaDigitadaCodificada  = CryptoJS.SHA256(SenhaDigitada);

//Se a SenhaDigitadaCodificada for igual a SenhaOriginalCodificada E a dataAtual for maior ou igual a Permitida
if(SenhaDigitadaCodificada == SenhaOriginalCodificada && DataAtual >= DataPermitida)
	
	//Se estiver certa
	{
		//mostra um alerta
		alert("acerto mizeravi");
		//Reseta os erros
		localStorage.QntErros = QntErros;
	}
	
	//Se a dataPermitida estiver a frente da atual
	else if (DataAtual < DataPermitida){
		let date = new Date(parseInt(localStorage.dataPermitida));
		let month = date.getMonth();
		let day = date.getDate();
		let year = date.getFullYear();
		let hour= date.getHours();
		let min= date.getMinutes();
		let sec= date.getSeconds();
		let allDate = hour+":"+min+":"+sec+" "+day+"/"+month+"/"+year
		alert("Ixe amigo, só poderá tentar novamente em "+allDate);
		//redireciona para outra página
		window.location.href = "http://www.google.com";
	}
	
	
	//Se acabaram os erros, agora só permite depois das horas de penalidade estabelecidas
	else if(localStorage.QntErros <= 1){
		//Reseta os erros
		localStorage.QntErros = 0;
		//Coloca o tempo de penalidade
		//localStorage.dataPermitida = Date.parse(new Date())+60*1000;
		localStorage.dataPermitida = Date.parse(new Date())+60*60*1000*HorasPenalidade;
		//redireciona para outra página
		window.location.href = "http://www.google.com";
		alert("Ixe amigo, você nao pode mais tentar durante um tempo");
	}
	
	
	else
	
	//Se estiver errada
	{
		//contabiliza o erro
		localStorage.QntErros = parseInt(localStorage.QntErros)-1;
		//mostra um alerta
		alert("errrrrrrroooo, você só tem mais "+localStorage.QntErros+" tentativas");
		//redireciona para outra página
		window.location.href = "http://www.google.com";
	}
	
	
</script>


<b>Pagina normal</b>

Search on these terms, it’s a very interesting area!

I hope I’ve helped!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.