/
crypto.go
54 lines (43 loc) · 1.05 KB
/
crypto.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
package pathutil
import (
"crypto"
"fmt"
"hash"
"io"
)
// Crypto method access hash funcionality like Path::Tiny Digest
// look to https://godoc.org/crypto#Hash for list possible crypto hash functions
//
// for example print of Sha256 hexstring
// hash, err := path.Crypto(crypto.SHA256)
// fmt.Println(hash.HexSum())
func (path PathImpl) Crypto(hash crypto.Hash) (c *CryptoHash, err error) {
reader, err := path.OpenReader()
if err != nil {
return nil, err
}
defer func() {
if errClose := reader.Close(); errClose != nil {
err = errClose
}
}()
h := hash.New()
_, err = io.Copy(h, reader)
if err != nil {
return nil, err
}
return &CryptoHash{h}, nil
}
// CryptoHash struct is only abstract for hash.Hash interface
// for possible use with methods
type CryptoHash struct {
hash.Hash
}
// BinSum method is like hash.Sum(nil)
func (hash *CryptoHash) BinSum() []byte {
return hash.Sum(nil)
}
// HexSum method retun hexstring representation of hash.Sum
func (hash *CryptoHash) HexSum() string {
return fmt.Sprintf("%x", hash.Sum(nil))
}