How to encrypt and decrypt string using Javascript

Last updated on February 21st, 2022 at 12:59 pm

Click to rate this tutorial!
[Total: 2 Average: 4]

Here we are discussing Javascript string encrypting and decrypting with demo. We have a text box in which you can enter the string ,click a button to encrypt and decrypt it . Very useful for GET queries that you would like to encrypt in the URI. It encrypts a string by converting each character to its ASCII key code. Supports two-way encryption – from a string to the numeric code, or from the numeric code back to the string.

<script LANGUAGE="JavaScript">
var str_in;
var str_out = "";
var num_in;
var num_out = "";
var e = "Enter Text!";
 
function str_to_num(form) {
num_out = "";
if(form.input.value == "") alert(e);
else {
str_in = escape(form.input.value);
for(i = 0; i < str_in.length; i++) {
num_out += str_in.charCodeAt(i) - 23;
}
form.output.value = num_out;
form.input.value = "";
   }
}
 
function num_to_str(form) {
str_out = "";
if(form.output.value == "") alert(e)
else {
num_out = form.output.value; 
for(i = 0; i < num_out.length; i += 2) {
num_in = parseInt(num_out.substr(i,[2])) + 23;
num_in = unescape('%' + num_in.toString(16));
str_out += num_in;
}
form.input.value = unescape(str_out);
form.output.value = "";
   }
}
</script>

HTML CODE

<center>
<form name=encryptform>
<table>
<tr>
<td align=center>Original String</td>
<td> </td>
<td align=center>Encrypted Code</td>
</tr>
<tr>
<td align=center><input name=input type=text size=40 value="Mistonline Encryption"/></td>
<td align=center>
<input type=button value="Decrypt" onClick="javascript:num_to_str(this.form)"/><br />
<input type=button value="Encrypt" onClick="javascript:str_to_num(this.form)"/>
</td>
<td align=center><input name=output type=text size=40/></td>
</tr>
</table>
</form>
</center>

DEMO

Click to rate this tutorial!
[Total: 2 Average: 4]

Leave a Reply

Your email address will not be published.