54 lines
1.2 KiB
Go
54 lines
1.2 KiB
Go
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}
|
|
}
|
|
|
|
func (h *Default256Hasher) QuizHashes(quiz *client.CreateQuizRequest) []string {
|
|
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
|
|
}
|
|
|
|
func (h *Default256Hasher) QuestionHash(question *client.CreateQuestionRequest) string {
|
|
return h.hashFn(question.Text)
|
|
}
|
|
|
|
func (h *Default256Hasher) AnswerHash(answer *client.CreateAnswerRequest) string {
|
|
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, ""))
|
|
}
|