What is Base 64 Encoder and Decoder?

Understanding Base 64 Encoder and Decoder?

What are Base64 Encoder and Decoder? You may have heard or even used it before, but may not know what exactly it is. Nowadays, on the internet, Base64 is generally and heavily used to prevent data corruption in applications including email and complex data encryption. In this article, we will comprehensively discuss what Base 64 is, and how does it works, follow by a step-by-step guide on creating a useful Base 64 Encoder & Decoder API to save your day on projects! Read on!

What is Base 64?

Base 64 is defined as an encoding and decoding technique to convert binary data to an American Standard for Information Interchange (ASCII) text format, and vice versa. In terms of mathematics, the base of a number system means how many different characters represent numbers. The concept of “encoding” intuitively comes from the mathematical definition of bases: “we have 64 characters that represent numbers.”

Let’s break down the Base 64 character set: 

  • 26 uppercase letters 
  • 26 lowercase letters 
  • 10 numbers 
  • +    and     /     for new lines 

The term Base 64 originates from Multipurpose Internet Mail Extension(MIME) content transfer encoding. Base 64 is also named as Privacy enhanced Electronic mail (PEM) as it is generally used in applications like email via MIME and complex data through XML.

Use cases of Base 64 Encoding and Decoding

1. Store or transfer data with a restricted set of characters

When you can’t pass an arbitrary value in each byte, you might need Base 64 to encode the data into an accessible value which are known to be safe to send without getting corrupted (ASCII alphanumeric characters and a couple of symbols). Email is an typical example.

2. Ensure effective communication

When we send over data, we cannot ensure that the data transmitted and interpreted in our desired format. In order to make sure that both sender and receiver understand, Base 64 can standardise the coded format and ensure the correctness.

Python Base 64 encoding

Simple Python program for Base 64 encoding text

Let’s have our first simple try on encode and decode text with Python. Noted that Python includes a module, BASE64. The module includes the following functions:

  • Base64.encode(input, output)
  • Base64.decode(input, output) 

Open a new file encoding.py, and add the following script to your IDE.

#encoding message
import base64
 
message = "Hello World"
message_bytes = message.encode('ascii')
base64_bytes = base64.b64encode(message_bytes)
base64_message = base64_bytes.decode('ascii')
 
print(base64_message)

In the above script, we used the module base64. Then we convert the string data into a bytes-like object using the string’s encode method and store it in a variable named message_bytes. After that, we use the base64.b64encode to encode message_bytes into a base64-bytes-like object and stored it in the variable base64_bytes. In the end, we just get our encoded message base64_message by using base64_bytes.decode.

Simply run the python file in your command line or terminal as below 

And then you will get the encoded string.

python3 encoding_text.py
SGVsbG8gV29ybGQ=

Now, let’s try decoding our data. Open a new file decoding.py, add the following script into your IDE

#decoding message
import base64
 
base64_message = 'SGVsbG8gV29ybGQ='
base64_bytes = base64_message.encode('ascii')
message_bytes = base64.b64decode(base64_bytes)
message = message_bytes.decode('ascii')
 
print(message)

Once again, we need the base64 module imported. And then we just decoded in an opposite direction of encoding. 

Run the python file in your command line or terminal as below 

And then you will get the human-readable decoded message.

$ python3 decoding_text.py
Hello World

What is an API?

We all know that there are somethings we just don’t want do it manually. That’s where APIs come in. An API, or application programming interface, is a set of rules and specifications that allow two software programs to communicate with each other. Developers can build applications that work seamlessly together and make it possible for end-users to complete complex tasks with just a few clicks. By using an API, you can save yourself time and effort of having to write your own code from scratch. Let’s take a closer look at what an API is and how you can use it in your own development projects. If you want to know more about what an API is, check this link out.

For example, imagine being able to book a flight, hotel, and rental car all in one place by using just a few taps on your smartphone. This would not be possible without APIs! As the world becomes increasingly interconnected, the importance of well-designed APIs will only continue to grow.

Create a simple Base 64 Encoder and Decoder API

Why should you choose this server?

The Base 64 Encoder and Decoder API is supported by FabriXAPI, an All-in-one API Platform that supports API Needs and it is certified as “AWS Qualified Software” since 2022. You can register for an API portal for free, share and monetise APIs easily on the trustable platform certified by ISO27001.

Prerequisites

You will need a suitable Base 64 encoder and decoder API provider. Using Open Image Lab’s Base 64 encoder and decoder API, you can proceed easily as follows :

1. Sign up for a Developer Account

You need to sign up to the API Portal in order to subscribe and access this API. For more information, please refer to “Register as a Developer“.

2. Active API Subscription

You need to subscribe to this API before consuming it. Many APIs come with a free trial plan so that you can experience the API functions provided free of charge. For more information, please refer to “Subscribe to APIs“.

3. API Credential

An API Key is required to access the API. It can be obtained in the Developer Admin Portal once you have completed the signup to FabriXAPI. For more information, please refer to “Create API Key“.

Endpoints

  • Encode
https://trial-api-base-64-encoder-and-decoder-2nzl.gw.openapihub.com/node-encoder/base64-decode
  • Decode
https://6833ec11-b251-4023-96d1-8fea243bf807-2nzl.gw.openapihub.com/node-encoder/base64-decode

You may check out the full API documentation here on the API Portal.

Make an UI Design for the API

a sample UI

First off, let’s make an attractive user interface for our Base 64 Encoder and Decoder API as above.

Simply follow the below HTML and put it on your IDE.

<div id="app">
  <div class="demo-description">
    <h2>Base 64 Encoder & Decoder</h2>
    <span>To protect your credentials.</span>
    <br>
    <span>DO NOT save this API Key in the code sandbox!!</span>
  </div>
  <div class="test-area">
    <div class="input-area">
      <span>API Key</span>
      <input
        type="text"
        placeholder="Input your key here"
        v-model="apikey"
      >
      <br>
       
      <span>Mode</span>
        <select v-model="mode">
          <option value="encode">Encode</option>
          <option value="decode">Decode</option>
        </select>
      <br>
 
      <span>Message to {{ modeText }}</span>
      <input
        type="text"
        placeholder="Message"
        v-model="input_string"
      >
      <br>
      <button v-on:click="generate">Convert</button>
    </div>
 
    <div class="output-area">
      <template v-if="error">
        <span v-html="error" />
      </template>
      <template v-else-if="!result">
        Fill in the Message (remember to select correct mode!) and API Key, then press "Convert".
      </template>
      <template v-else>
        <div v-html="result" />
      </template>
    </div>
  </div>
</div>

Apply CSS on the interface

Then, let’s give the UI a make up. Put some CSS into it. 

@import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600&display=swap');
body {
  background: #20262E;
  padding: 20px;
  font-family: 'Open Sans', sans-serif;
}
  
#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
  height: 400px;
}
  
.demo-description {
  text-align: center;
  margin-bottom: 20px;
}
  
.demo-description h2 {
  font-weight: semibold;
  margin-bottom: 5px;
}
  
.demo-description span {
  color: #999999;
}
  
.test-area {
  display: flex;
}
  
.input-area {
  text-align: right;
}
  
.input-area span {
  display: inline-block;
  line-height: 48px;
  margin-right: 8px;
  text-align: right;
  width: 150px;
}
  
.input-area input, select {
  border: 1px solid #999999;
  border-radius: 3px;
  height: 30px;
  width: 150px;
  padding: 0 7px;
}
 
.input-area select {
  height: 32px;
  width: 166px;
}
  
.input-area input::placeholder {
  color: #d0d0d0;
}
  
.input-area button {
  background-color: #57abf0;
  border: 0;
  border-radius: 4px;
  color: #ffffff;
  font-weight: 600;
  margin-top: 15px;
  width: 166px;
  padding: 15px 10px;
}
  
.output-area {
  color: #505050;
  font-size: 14px;
  margin: 20px;
  margin-right: 0px;
  width: calc(100% - 350px);
}
  
@media screen and (max-width: 616px) {
  .input-area {
    text-align: center;
  }
 
  .input-area span {
    text-align: left;
  }
    
  .output-area {
    width: calc(100% - 150px);
  }
    
  .input-area button {
    width: 140px;
    padding: 10px 7px;
  }
}
  
.output-area svg {
  transform: scale(0.7) translateX(-30px) translateY(-95px);
}

Interact the UI with Vue.js

This is the sample full script of the Vue.js for making a API request. You may try it out.

const endpoint = 'https://trial-api-base-64-encoder-and-decoder-2nzl.gw.openapihub.com/node-encoder/base64-';
 
new Vue({
    el: '#app',
    data() {
    return {
      input_string: '',
      mode: 'encode',
      apikey: '',
      result: '',
      error: ''
    }
  },
  computed: {
    modeText() {
        return this.mode.charAt(0).toUpperCase() + this.mode.substring(1)
    }
  },
  methods: {
    generate: function() {
      const axiosConfig = {
        headers: {
          'content-type': 'application/json',
          'x-openapihub-key': this.apikey
        }
      }
       
      const requestBody = {
        'inputString': this.input_string
      }
     
    axios.post(`${endpoint}${this.mode}`, requestBody, axiosConfig)
        .then(res => {
        this.error = ''
        this.result = `Parsed Message -<br>${res.data}`
      }).catch(err => {
          this.error = `Error occurred -<br>${err.response.data.message}`
          console.log('Error', err.response.data.message)
      })
    }
  }
})

Encode and Decode your first piece of data now

Now that we have all the materials prepared. Let’s have a try on our work.

Simply fill in the Message (remember to select correct mode!) and API Key, then press “Convert”.  Swiftly, you can get your encoded/decoded data! 

And the output is as follows:
a sample output of Base 64 encoding

Conclusion

That’s all for today! Now that you know a little more about Base 64 Encoder and Decoder, and how to create your own powerful API to handle sensitive text or data. If you want to skip the DIY and try the API at once, head over to the FabriXAPI API Portal and check it out.

Discover more from OpenAPIHub Community

Subscribe now to keep reading and get access to the full archive.

Continue reading