StoreBackEnd/pkg/utils/SHA.go

54 lines
1.1 KiB
Go
Raw Permalink Normal View History

2022-03-15 17:11:31 +01:00
package utils
/**
* SHA-256 Hashing Class
*
* @author Jérémi N <contact@enmove.eu>
* @version 1.0
*/
import (
"bufio"
"crypto/sha256"
"errors"
"fmt"
"io"
"os"
"strings"
)
// HashStream Make a fingerprint of a stream.
func HashStream(in *bufio.Reader) (string, error) {
sha := sha256.New()
if _, err := io.Copy(sha, in); err != nil {
return "", errors.New("unable to copy data into hashing system")
}
return fmt.Sprintf("%x", sha.Sum(nil)), nil
}
// HashFile Make a fingerprint of a file content.
func HashFile(filePath string) (string, error) {
file, err := os.Open(filePath)
if err != nil {
return "", err
}
defer file.Close()
hash, err := HashStream(bufio.NewReader(file))
if err != nil {
return "", err
}
return hash, nil
}
// HashFileCompare Make a fingerprint of a file and compare with the renseigned fingerprint.
func HashFileCompare(filePath string, fingerprint string) (bool, error) {
fileFingerprint, err := HashFile(filePath)
if err != nil {
return false, err
}
2022-03-20 15:32:45 +01:00
2022-03-15 17:11:31 +01:00
if strings.Compare(fileFingerprint, fingerprint) == 0 {
return true, nil
}
return false, nil
}