LanguagesAn Introduction to Cryptography in Go

An Introduction to Cryptography in Go

The Go standard library provides excellent support for cryptography and hashing. The root package for cryptography in Go is crypto, and it has a number of sub packages, such as aes, cipher, sha, and rsa to name but a few. Also, there is a package called hash, which provides Golang developers with a common interface implemented by all hash functions such as MD5, SHA256, and Hashing with Key (HMAC). Here, in this Go cryptography tutorial, we introduce the libraries associated with cryptography, with a brief detour on cryptographic programming concepts in general.

What is Cryptography?

In this digital world, data is the most important – as well as most vulnerable – element to exploit from a security point of view. Digital transmission of data over networks is prone to attacks by malicious actors who can exploit it to their own advantage. Personal or confidential information of the companies and their customers are vulnerable to prying eyes, especially when they are transmitted over a public network or internet.

Network security may secure the transmission, but data but the data element at the receiving end may fall into the wrong hands or be intruded upon in the process of transmission. Cryptography is a tool that helps developers to encode data into an undecipherable form, which, even if it falls into the wrong recipient’s hands, can safeguard it and make it indecipherable. The rightful owner of the data, on the other hand, has the key to decrypt it and get the information in its original form.

Encryption in Go

What cryptography basically does is scramble the data using a complex encryption algorithm. There are different types of cryptographic algorithms available to ensure privacy and security. They work on four basic principles: data confidentiality, integrity, availability and access control. The mathematical complexity of the encryption algorithm underpins the robustness of the mechanism. However, like any mechanism, the encryption can also be broken, but it is very difficult and costly. Nonetheless, it is a very useful mechanism to ensure data security and privacy. Some common cryptographic algorithms include AES, DES, and RSA.

Read: Understanding Functions in Go

Go Cryptography Code Examples

The crypto library of Go provides implementation for a number of cryptographic algorithms such as AES, Cipher, SHA, and RSA. Here is a quick use of the AES function. The acronym AES stands for Advanced Encryption Standard and was created by the NIST (National Institute of Standards and Technology) in October 2000. It is a block cipher technique where a plaintext is processed in blocks of 16 bytes. Each block is encrypted separately using a key of 32 bit length. Go provides functions that implement AES algorithms, – programmers can invoke them in their Go programs as shown in the following Golang code example:

package main

import (
	"crypto/aes"
	"encoding/hex"
	"fmt"
)

func encryptMessage(key string, message string) string {
	c, err := aes.NewCipher([]byte(key))
	if err != nil {
		fmt.Println(err)
	}
	msgByte := make([]byte, len(message))
	c.Encrypt(msgByte, []byte(message))
	return hex.EncodeToString(msgByte)
}

func decryptMessage(key string, message string) string {
	txt, _ := hex.DecodeString(message)
	c, err := aes.NewCipher([]byte(key))
	if err != nil {
		fmt.Println(err)
	}
	msgByte := make([]byte, len(txt))
	c.Decrypt(msgByte, []byte(txt))

	msg := string(msgByte[:])
	return msg
}

func main() {

	plainText := "This is a secret"                  
	key := "this_must_be_of_32_byte_length!!"

	emsg := encryptMessage(key, plainText)
	dmesg := decryptMessage(key, emsg)

	fmt.Println("Encrypted Message: ", emsg)
	fmt.Println("Decrypted Message: ", dmesg)

}

Running this code in your integrated development environment will produce the following output:

Encrypted Message:  319d4fa655ed543b4aa0d1efdc3619d8
Decrypted Message:  This is a secret

Read: Intro to Database Programming with Go

Hashing in Go

Hashing is another technique associated with cryptography. It is used to transform a given key or set of characters into another value. Hashing is particularly used in creating hash tables. It is basically a mathematical algorithm that helps in transforming one value to another. Apart from its many other uses in computing – such as storage and optimal searches – hashing can be quite effectively used in data encryption.

A cryptographic hash function can transform data of an arbitrary size into a fixed size output called cipher text. Hash functions are good for password encryption, which then can be stored as hash values. Understand that, unlike other cryptographic algorithms, a hashed cryptographic output is irreversible. For example, this means that to compare a password stored in the database with an authenticating password, it must first be encrypted and then compared with the stored password. Common hashing algorithms include: SHA1 (Secure Hashing Algorithm 1), SHA256 (Secure Hashing Algorithm 256), and MD5.

Go Hashing Code Example

The MD5 – or Message Digest Message 5 – is a one-way encryption algorithm where a 128-bit hash function is used to generate a value or digest from a string of any length. It was designed by Ronald Rivest in 1991 for digital signature verification. The output of their hash function is represented as a digest of 32-bit hexadecimal numbers. Here is a quick implementation of the md5 function in Go using the crypto/md5 library:

package main

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
)

func getMD5Hash(message string) string {
	hash := md5.Sum([]byte(message))
	return hex.EncodeToString(hash[:])
}

func main() {
	mypassword := "secret"
	fmt.Println("MD5 Hashed value: ", getMD5Hash(mypassword))

}

Here is the output from running this code in your code editor:

MD5 Hashed value:  5ebe2294ecd0e0f08eab7690d2a6ee69

Final Thoughts on Go Encryption and Golang Hashing

The specification for data encryption algorithms are complex and are an object of much research in most cases. Golang, however, provides a dedicated library that implements a number of popular cryptographic algorithms in the form of functions. Programmers can invoke these Go cryptography libraries as required and focus on the business logic at hand, rather than go hunting for their own implementation. The Golang crypto library functions are, therefore, a convenient tool to use cryptographic implementation in Go software development.

Read more Go and Golang programming tutorials and guides.

Latest Posts

Related Stories