Encryption / Decryption in Javascript

Introduction:
As as web Developer some times you need encryption and Decryption in Java Script. for this purpose a quick code snap is given below.




Solution:

Java Script Encryption Function:


function Encrypt(PlainText, Key) 
{
            var to_enc = PlainText.toString().replace(/^\n+/, "").replace(/\n+$/, "");

            var xor_key = Key;
            var the_res = "";
            for (i = 0; i < to_enc.length; ++i) {

                if (to_enc.charCodeAt(i) <= 32) {
                    the_res += String.fromCharCode((to_enc.charCodeAt(i)));
                }
                else {

                    the_res += String.fromCharCode((to_enc.charCodeAt(i)) - Key);
                }
            }
            return (the_res);

 }

Java Script Decryption Function:

function Decrypt(CipherText, Key) 
{
            var to_dec = CipherText;
            var xor_key = Key;
            var PlainText = "";
            for (i = 0; i < to_dec.length; i++) {


                if (to_dec.charCodeAt(i) <= 32) {
                    PlainText += String.fromCharCode((to_dec.charCodeAt(i)));
                }
                else {

                    PlainText += String.fromCharCode((to_dec.charCodeAt(i)) + Key);
                }

            }

            return (PlainText);
}

Key points for use:
  • Provide same key in both function for Encryption and Decryption.

Follow us on below channels to stay updated for new post and tutorials:
Blog: http://easytutorials4all.blogspot.com
Google+ : https://plus.google.com/u/0/112994256924713874536
Facebook Page : https://facebook.com/EasyTutorials4All
Youtube: https://www.youtube.com/channel/UCod8G-TeTUTz9DjaqK1C5-g

Comments

Popular posts from this blog

Encrypt data in browser with Javascript and Decrypt on server with asp.net c#