Generate SHA1 hash of a file in Golang example

08 April, 2016

This function is based on my previous post but adapted for the SHA1 algorithm.

A Golang function

The argument you have to specify in the following function is the path to the file you desire to hash (the absolute path or relative path), and the output is either an empty string with an error, or a string with 40 characters and a nil error.

import (
	"crypto/md5"
	"encoding/hex"
	"io"
	"os"
)
func hash_file_sha1(filePath string) (string, error) {
	//Initialize variable returnMD5String now in case an error has to be returned
	var returnSHA1String string
	
	//Open the filepath passed by the argument and check for any error
	file, err := os.Open(filePath)
	if err != nil {
		return returnSHA1String, err
	}
	
	//Tell the program to call the following function when the current function returns
	defer file.Close()
	
	//Open a new SHA1 hash interface to write to
	hash := sha1.New()
	
	//Copy the file in the hash interface and check for any error
	if _, err := io.Copy(hash, file); err != nil {
		return returnSHA1String, err
	}
	
	//Get the 20 bytes hash
	hashInBytes := hash.Sum(nil)[:20]
	
	//Convert the bytes to a string
	returnSHA1String = hex.EncodeToString(hashInBytes)
	
	return returnSHA1String, nil

}

Example

This example calculates the MD5 hash of itself, the running program.

package main

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

func hash_file_sha1(filePath string) (string, error) {
	var returnSHA1String string
	file, err := os.Open(filePath)
	if err != nil {
		return returnSHA1String, err
	}
	defer file.Close()
	hash := sha1.New()
	if _, err := io.Copy(hash, file); err != nil {
		return returnSHA1String, err
	}
	hashInBytes := hash.Sum(nil)[:20]
	returnSHA1String = hex.EncodeToString(hashInBytes)
	return returnSHA1String, nil

}

func main() {
	hash, err := hash_file_sha1(os.Args[0])
	if err == nil {
		fmt.Println(hash)
	}
}