Mise en place système de hashage

This commit is contained in:
2022-03-15 17:11:31 +01:00
parent 6c33573ad1
commit 02de46bed2
7 changed files with 72 additions and 48 deletions

View File

@@ -18,6 +18,7 @@ func ReceiveFile(path string, fileSize int, reader *bufio.Reader) bool {
buffer := make([]byte, 1024)
currentSize := 0
// Copy file
b, done := copyFile(currentSize, fileSize, reader, buffer, file)
if done {
return b

View File

@@ -1,34 +0,0 @@
package utils
import (
"bufio"
"crypto/sha256"
"fmt"
"io"
"log"
"os"
)
func HashFileCompare(path string, fingerPrint string) bool {
sum := GenFingerPrint(path)
return fingerPrint == fmt.Sprintf("%x", sum)
}
func GenFingerPrint(path string) []byte {
f, err := os.Open(path)
if err != nil {
log.Fatal(err)
}
defer f.Close()
input := bufio.NewReader(f)
hash := sha256.New()
if _, err := io.Copy(hash, input); err != nil {
log.Fatal(err)
}
sum := hash.Sum(nil)
return sum
}

52
pkg/utils/SHA.go Normal file
View File

@@ -0,0 +1,52 @@
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
}
if strings.Compare(fileFingerprint, fingerprint) == 0 {
return true, nil
}
return false, nil
}