Base64 Encoding and Decoding in Golang

Go supports base64 encoding and decoding out of the box. In this post, we are going to use the base64 encoder and decoder to create and use one of the most used encodings in Computer Science.

What is encoding?

Encoding is the way to convert one form of information to another form in a reversible manner. That means the data can be decoded by using the same algorithm that encoded it. It must not be confused with encryption which is done in a way that the data can’t be decoded without using a key thus making it extremely secure. Encryption is a type of encoding.

The base64 encoding

The base64 encoding uses a symbol table of 64 characters that includes A-Z, a-z, 0-9, +, /, =. A total of 64 characters are used to encode the data into a string containing those symbols.

The imports required for base64 encoding

The encoding package in Go contains the base64 package. So, we need to import it first.

import "encoding/base64"

Encode data to base64 in Golang

To convert a string to a base64 we first need to convert it to a byte slice. Here is an example of a simple string converted to base64.

package main

import (
	"encoding/base64"
	"fmt"
)

func main() {

	s := "a string"

	se := base64.StdEncoding.EncodeToString([]byte(s))
	fmt.Println(se)                                        // YSBzdHJpbmc=
}

Decode data using the base64 package

The decoding is really easy. The process is the same and uses the standard decoder from the package to decode the string.

package main

import (
	"encoding/base64"
	"fmt"
)

func main() {

	s := "a string"

	se := base64.StdEncoding.EncodeToString([]byte(s))
	fmt.Println(se)                                        // YSBzdHJpbmc=
	
	sd, e := base64.StdEncoding.DecodeString(se)
	if e != nil {
		fmt.Println(e)
	}
	fmt.Println(string(sd))                                // a string                        
}

Recommended: AES Encryption in Golang