probo/hasher/sha256/sha256.go

55 lines
1.1 KiB
Go
Raw Normal View History

2022-06-24 18:56:06 +02:00
package sha256
import (
"crypto/sha256"
"fmt"
"sort"
"strings"
"git.andreafazzi.eu/andrea/probo/client"
"git.andreafazzi.eu/andrea/probo/hasher"
)
var DefaultSHA256HashingFn = func(text string) string {
return fmt.Sprintf("%x", sha256.Sum256([]byte(text)))
}
type Default256Hasher struct {
hashFn hasher.HashFunc
}
func NewDefault256Hasher(hashFn hasher.HashFunc) *Default256Hasher {
return &Default256Hasher{hashFn}
}
2022-06-28 13:49:35 +02:00
func (h *Default256Hasher) QuizHashes(quiz *client.Quiz) []string {
2022-06-24 18:56:06 +02:00
result := make([]string, 0)
result = append(result, h.QuestionHash(quiz.Question))
for _, a := range quiz.Answers {
result = append(result, h.AnswerHash(a))
}
result = append(result, h.Calculate(result))
return result
}
2022-06-28 13:49:35 +02:00
func (h *Default256Hasher) QuestionHash(question *client.Question) string {
2022-06-24 18:56:06 +02:00
return h.hashFn(question.Text)
}
2022-06-28 13:49:35 +02:00
func (h *Default256Hasher) AnswerHash(answer *client.Answer) string {
2022-06-24 18:56:06 +02:00
return h.hashFn(answer.Text)
}
func (h *Default256Hasher) Calculate(hashes []string) string {
orderedHashes := make([]string, len(hashes))
copy(orderedHashes, hashes)
sort.Strings(orderedHashes)
return h.hashFn(strings.Join(orderedHashes, ""))
}