summaryrefslogtreecommitdiff
path: root/internal/utils/hashing.go
blob: 86e0129f3471788693479ecede4884a2c5100c29 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package utils

import (
	"crypto/sha256"
	"encoding/hex"
	"io"
	"os"
)

// HashSHA256FromString takes an input string and calculates the SHA256 checksum returning it as a base16 hash string.
func HashSHA256FromString(input string) (output string) {
	hash := sha256.New()

	hash.Write([]byte(input))

	return hex.EncodeToString(hash.Sum(nil))
}

// HashSHA256FromPath takes a path string and calculates the SHA256 checksum of the file at the path returning it as a base16 hash string.
func HashSHA256FromPath(path string) (output string, err error) {
	file, err := os.Open(path)
	if err != nil {
		return "", err
	}

	defer file.Close()

	hash := sha256.New()

	if _, err := io.Copy(hash, file); err != nil {
		return "", err
	}

	return hex.EncodeToString(hash.Sum(nil)), nil
}