-
Notifications
You must be signed in to change notification settings - Fork 36
/
algorithms.go
62 lines (49 loc) · 1.33 KB
/
algorithms.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
package crypto
import (
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"fmt"
"hash"
"io"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
)
var (
DigestAlgorithmSHA1 Algorithm = algorithmSHAImpl{"sha1"}
DigestAlgorithmSHA256 Algorithm = algorithmSHAImpl{"sha256"}
DigestAlgorithmSHA512 Algorithm = algorithmSHAImpl{"sha512"}
)
type algorithmSHAImpl struct {
name string
}
func (a algorithmSHAImpl) Name() string { return a.name }
func (a algorithmSHAImpl) CreateDigest(reader io.Reader) (Digest, error) {
hash := a.hashFunc()
_, err := io.Copy(hash, reader)
if err != nil {
return nil, bosherr.WrapError(err, "Copying file for digest calculation")
}
return NewDigest(a, fmt.Sprintf("%x", hash.Sum(nil))), nil
}
func (a algorithmSHAImpl) hashFunc() hash.Hash {
switch a.name {
case "sha1":
return sha1.New()
case "sha256":
return sha256.New()
case "sha512":
return sha512.New()
default:
panic("Internal inconsistency")
}
}
type unknownAlgorithmImpl struct {
name string
}
func NewUnknownAlgorithm(name string) unknownAlgorithmImpl {
return unknownAlgorithmImpl{name: name}
}
func (c unknownAlgorithmImpl) Name() string { return c.name }
func (c unknownAlgorithmImpl) CreateDigest(reader io.Reader) (Digest, error) {
return nil, bosherr.Errorf("Unable to create digest of unknown algorithm '%s'", c.name)
}