How to encrypt password on client side using Javascript
In this tutorial, I will discuss password encryption on the client side using javascript. For client-side encryption, you have to use two javascript.
1 2 |
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js"></script> <script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/md5.js"></script> |
HTML FORM
1 2 3 4 5 6 |
<form class="form-signin" method="post" name="signin" id="signin"> <input type="password" name="password" id="password" placeholder="Password" id="password" value="" /> <input type="hidden" name="hide" id="hide" /> <div style="color:red" id="err"></div> <input type="submit" name="login" type="submit" onclick="return encrypt()" value="Submit" > </form> |
In this form I created one password field and one hidden field. Hidden field is used for hold the value of actual password.
Javascrit for encryption
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<script> function encrypt() { var pass=document.getElementById('password').value; var hide=document.getElementById('hide').value; if(pass=="") { document.getElementById('err').innerHTML='Error:Password is missing'; return false; } else { document.getElementById("hide").value = document.getElementById("password").value; var hash = CryptoJS.MD5(pass); document.getElementById('password').value=hash; return true; } } </script> |
In the above javascript, I created a function encrypt(). I call this function on the click to submit button.
Here is the full code that we have written during this tutorial:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<html> <head> <title>Encrypt Password on client Side</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js"></script> <script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/md5.js"></script> <script> function encrypt() { var pass=document.getElementById('password').value; var hide=document.getElementById('hide').value; if(pass=="") { document.getElementById('err').innerHTML='Error:Password is missing'; return false; } else { document.getElementById("hide").value = document.getElementById("password").value; var hash = CryptoJS.MD5(pass); document.getElementById('password').value=hash; return true; } } </script> </head> <body> <form class="form-signin" method="post" name="signin" id="signin"> <input type="password" name="password" id="password" placeholder="Password" id="password" value="" /> <input type="hidden" name="hide" id="hide" /> <div style="color:red" id="err"></div> <input type="submit" name="login" type="submit" onclick="return encrypt()" value="LOGIN" > </form> </body> </html> |