Go: compute the SHA-256 hash of a string

Go: compute the SHA-256 hash of a string

In this article, we'll explore how to create a hexadecimal string containing the SHA-256 hash of a string using the Go programming language.

In the modern world of programming, data security and integrity are of paramount importance. One of the most widely used techniques to ensure data integrity is cryptographic hashing, and the SHA-256 (Secure Hash Algorithm 256-bit) algorithm is one of the most common choices for this purpose. In this article, well explore how to create a hexadecimal string containing the SHA-256 hash of a string using the Go programming language.

SHA-256 is a cryptographic hashing algorithm that takes data of any length as input and produces a fixed hexadecimal string of 64 characters. SHA-256 hashing is known for its resistance to collisions (when two different inputs produce the same hash) and its ability to generate random, unique hashes that securely represent the input. This makes it ideal for verifying data integrity and information validity.

Go is a modern programming language that offers a robust and flexible standard library. To compute the SHA-256 hash of a string in Go, we can use the crypto/sha256 package which provides all the necessary functionality. Heres how to create a hex string containing the SHA-256 hash of a string:


package main

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

func main() {
	inputString := "Hello, world!"
	hash := sha256.Sum256([]byte(inputString))
	hashString := hex.EncodeToString(hash[:])

	fmt.Println("Input String:", inputString)
	fmt.Println("SHA-256 Hash:", hashString)
}

In the above code:

  1. We import the necessary packages, crypto/sha256 to compute the hash and encoding/hex to convert the hash to a hexadecimal string.
  2. We define the input string we want to hash.
  3. We use sha256.Sum256 to compute the SHA-256 hash of the input. This function returns a fixed-length byte array, so we need to convert it to a human-readable hexadecimal string using hex.EncodeToString .
  4. We print both the input string and the resulting SHA-256 hash.

Conclusion

Computing the SHA-256 hash of a string is a common practice to ensure data integrity and verify its authenticity. Go greatly simplifies this task thanks to its well-designed standard library. Throughout this article, weve explored how to use the crypto/sha256 and encoding/hex package to calculate the SHA-256 hash of a string and convert it to a hexadecimal string. By integrating this knowledge into your applications, you can improve the security and reliability of your data.