SHA-1 (Secure Hash Algorithm) is a cryptographic hash function designed by the United States National Security Agency and published by the National Institute of Standards and Technology as a Federal Information Processing Standard. SHA-1 generates a 160-bit (20-byte) hash value known as a message digest, typically represented as 40 hexadecimal characters.

This article demonstrates SHA-1 hash calculation using Go's standard library crypto/sha1.

Calculating SHA-1

The complete source code for calculating SHA-1 using crypto/sha1 is shown below. The encoding/hex package is used to convert the byte slice to a hexadecimal string:

package main

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

func SHA1(s string) string {
	// Create a new SHA-1 hash object
	o := sha1.New()

	// Write the input string bytes to the hash object
	o.Write([]byte(s))

	// Get the final hash sum and encode to hex string
	return hex.EncodeToString(o.Sum(nil))
}

func main() {
	// Calculate and print SHA-1 of "123456"
	fmt.Println(SHA1("123456"))
}

Program Output

7c4a8d09ca3762af61e59520943dc26494f8941b