Cyber Security

Base64 encode decode using JavaScript

 Base64 is a encryption method to encrypt original content to a unreadable format and arrangement of characters. Base64 is very good encryption method in my opinion to protect any valuable and important string from being copied. you can learn more about base64 from Wikipedia.


What need of base64 encryption in Programming

some time when we write a code or script then we need some function to protect original code or string which is important to us. Encrypting a string and code will help you to get rid by script kiddies who just copy your script as it is and use it in there websites and codes, but by encrypting a string or a piece of code script kiddies will not copy your code because of encryption. Other important use of it is you can protect code from being modified by other programmers,or users.


Base64 encryption Example - 

Here i will show you the original and encrypted string.

orignal String or text = hello world!

encrypted in base64 = SGVsbG8gV29ybGQh

As you can clearly see that original string is clear , readable and understandable, but encoded/encrypted string is not readable and not understandable its like someone put the random characters in a line.

Hope You get this. Now we will learn that how can we convert a simple string to encrypted base64 string using a one line JavaScript code.


How encode a string in base64 using JavaScript 

JavaScript is amazing programming language. We will use window.btoa() javascript code for encoding a string.

var string = "itscybertech"

var encodedstr = window.btoa(string);

document.write(encodedstr);

In the above java script code we are encoding the "itscybertech" using window.btoa() method. and after that to display the encoded string we are using document.write() function.

If you will run this code you will get a string - aXRzY3liZXJ0ZWNo this is the base64 encryption of string itscybertech.


How decode a string in base64 using JavaScript 

We will use window.atob() javascript code for decoding a string.

var encodedstring = "aXRzY3liZXJ0ZWNo";

var DEcodedstr = window.atob(encodedstring);

document.write(DEcodedstr);

In the above java script code we are decoding the "aXRzY3liZXJ0ZWNo" using window.atob() method. and after that to display the decoded string we are using document.write() function.

If you will run this code you will get a string - itscybertech this is the original string.


Important -  Remember For Encoding a string  use - window.btoa() And for decoding a encrypted/encoded string use window.atob()

Learn: Window location function full guide JavaScript