-
Notifications
You must be signed in to change notification settings - Fork 3
/
hash.go
57 lines (47 loc) · 1.08 KB
/
hash.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// Copyright (c) 2022 Dmitry Tkachenko (tkachenkodmitryv@gmail.com)
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package care
import (
"crypto/sha256"
"errors"
"fmt"
"hash/crc32"
)
type Hash interface {
Calc(key string) (string, error)
}
const (
maxKeySuze = 1024 * 1024
hashPiecesDelimiter = "_"
)
type defaultHash struct {
crc32Table *crc32.Table
}
func (s *defaultHash) Calc(key string) (string, error) {
keyLen := len(key)
if keyLen < 1 {
return "", errors.New("You can't calc the hash from an empty string.")
}
if keyLen > maxKeySuze {
return "", errors.New(fmt.Sprintf(
"The key contains %d characters, but the one must be less than %d characters.",
keyLen,
maxKeySuze,
))
}
data := []byte(key)
crc32Hash := crc32.Checksum(data, s.crc32Table)
sha256Hash := sha256.Sum256(data)
hash := fmt.Sprintf("%08x%s%x",
crc32Hash,
hashPiecesDelimiter,
sha256Hash,
)
return hash, nil
}
func newDefaultHash() Hash {
return &defaultHash{
crc32Table: crc32.MakeTable(crc32.Castagnoli),
}
}