Base64 encode and decode
Base64 encode
Copied
Base64 is binary-to-text conversion strategy that allows to send text in multiple media channels without breaking the meaning of data.
Keypoints of base64
1. Base64 is not providing security.
2. Base64 encode not compress data, but it increases data size.
Python
import base64
input_str = 'This is simple text'
input_byte_str = input_str.encode('ascii')
base64_bytes = base64.b64encode(input_byte_str)
base64_str = base64_bytes.decode('ascii')
print(f'Encoded string: {base64_str}')
###########
import base64
input_str = 'VGhpcyBpcyBzaW1wbGUgdGV4dA=='
input_byte_str = input_str.encode('ascii')
output_bytes = base64.b64decode(input_byte_str)
output_str = output_bytes.decode('ascii')
print(f'Decoded string: {output_str}')
JavaScript
var input_str = 'This is simple text';
// Encode the String
var encoded_str = btoa(input_str);
console.log(encoded_str); // Outputs: 'VGhpcyBpcyBzaW1wbGUgdGV4dA=='
// Decode the String
var decoded_str = atob(encoded_str);
console.log(decoded_str); // Outputs: 'This is simple text'
NodeJs
let input_str = Buffer.from('This is simple text').toString('base64');
console.log(input_str);
let output_str = Buffer.from(input_str, 'base64').toString();
console.log(output_str);
Java
String inputStr = 'This is simple text';
String encodedString = Base64.getEncoder().encodeToString(inputStr.getBytes());
byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
String decodedStr = new String(decodedBytes);