Refactored the SHA256 algorithm and updated it so it now returns the hash in hexadecimal.

main
Tylan Tyson 12 months ago
parent 773e96ef37
commit 3f16795eb7

@ -4,7 +4,7 @@ package sha256
type Algorithm struct{} type Algorithm struct{}
// New // New
func New(size int) Algorithm { func New() Algorithm {
// Return Algorithm // Return Algorithm
return Algorithm{} return Algorithm{}
} }

@ -4,10 +4,11 @@ import (
// Standard // Standard
"crypto/sha256" "crypto/sha256"
"crypto/subtle" "crypto/subtle"
"encoding/hex"
) )
// Check Hash // Check Hash
func (Algorithm) CheckHash(data []byte, hashToCheck []byte) (bool, error) { func (Algorithm) CheckHash(data []byte, hashToCheck string) (bool, error) {
// Hasher // Hasher
hasher := sha256.New() hasher := sha256.New()
// Write To Hasher // Write To Hasher
@ -16,6 +17,12 @@ func (Algorithm) CheckHash(data []byte, hashToCheck []byte) (bool, error) {
if err != nil { if err != nil {
return false, err return false, err
} }
// Decode Hash To Check
decodedHashToCheck, err := hex.DecodeString(hashToCheck)
// Handle Error
if err != nil {
return false, err
}
// Return Hash // Return Hash
return subtle.ConstantTimeCompare(hasher.Sum(nil), hashToCheck) == 1, err return subtle.ConstantTimeCompare(hasher.Sum(nil), decodedHashToCheck) == 1, err
} }

@ -3,18 +3,19 @@ package sha256
import ( import (
// Standard // Standard
"crypto/sha256" "crypto/sha256"
"encoding/hex"
) )
// Hash // Hash
func (Algorithm) Hash(data []byte) ([]byte, error) { func (Algorithm) Hash(data []byte) (string, error) {
// Hasher // Hasher
hasher := sha256.New() hasher := sha256.New()
// Write To Hasher // Write To Hasher
_, err := hasher.Write(data) _, err := hasher.Write(data)
// Handle Error // Handle Error
if err != nil { if err != nil {
return []byte(""), err return "", err
} }
// Return Hash // Return Hash
return hasher.Sum(nil), err return hex.EncodeToString(hasher.Sum(nil)), err
} }

Loading…
Cancel
Save