-
Notifications
You must be signed in to change notification settings - Fork 10
/
sha384.go
88 lines (68 loc) · 1.61 KB
/
sha384.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package sha384
import (
"bytes"
"crypto/sha512"
stdhash "hash"
"io"
"os"
"sort"
"github.com/pkg/errors"
"github.com/simplesurance/baur/digest"
)
// Hash offers an interface to add data for computing a digest
type Hash struct {
hash stdhash.Hash
}
// New returns a sha384.Hash to compute a digest
func New() *Hash {
return &Hash{hash: sha512.New384()}
}
// AddFile reads a file and adds it to the hash
func (h *Hash) AddFile(path string) error {
f, err := os.Open(path)
if err != nil {
return errors.Wrap(err, "opening file failed")
}
defer f.Close()
if _, err := io.Copy(h.hash, f); err != nil {
return errors.Wrap(err, "reading file failed")
}
return nil
}
// Digest returns the digest of the hash
func (h *Hash) Digest() *digest.Digest {
sum := h.hash.Sum(nil)
return &digest.Digest{
Algorithm: digest.SHA384,
Sum: sum,
}
}
// AddBytes add bytes to the hash
func (h *Hash) AddBytes(b []byte) error {
_, err := h.hash.Write(b)
if err != nil {
return errors.Wrap(err, "writing to hash stream failed")
}
return nil
}
// Sum aggregates multiple digests to a single SHA384 digest
func Sum(digests []*digest.Digest) (*digest.Digest, error) {
hash := New()
buf := bytes.Buffer{}
sort.Slice(digests, func(i, j int) bool {
if digests[i].Algorithm < digests[j].Algorithm {
return true
}
if digests[i].Algorithm > digests[j].Algorithm {
return false
}
return bytes.Compare(digests[i].Sum, digests[j].Sum) == -1
})
for _, d := range digests {
buf.WriteString(d.String())
}
if err := hash.AddBytes(buf.Bytes()); err != nil {
return nil, err
}
return hash.Digest(), nil
}