-
Notifications
You must be signed in to change notification settings - Fork 2
/
hash.go
119 lines (105 loc) · 2.06 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
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package filter
import (
"bytes"
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"encoding/base64"
"fmt"
"hash"
"io"
"strings"
"github.com/koron/nvgd/resource"
)
// Hash represents hash filter.
type Hash struct {
Base
s int
h hash.Hash
enc hashEncoder
}
type hashEncoder func(io.Writer, []byte) error
// NewHash creates a hash filter instance.
func NewHash(r io.ReadCloser, h hash.Hash, enc hashEncoder) *Hash {
f := &Hash{
s: 0,
h: h,
enc: enc,
}
f.Base.Init(r, f.readNext)
return f
}
func (f *Hash) readNext(buf *bytes.Buffer) error {
if f.s == 2 {
return io.EOF
}
if f.s == 0 {
if err := f.readAll(); err != nil {
return err
}
f.s = 1
}
if err := f.enc(buf, f.h.Sum(nil)); err != nil {
return err
}
f.s = 2
return nil
}
func (f *Hash) readAll() error {
_, err := io.Copy(f.h, f.Reader)
return err
}
func toHash(n string) (hash.Hash, error) {
switch strings.ToLower(n) {
case "md5":
return md5.New(), nil
case "sha1":
return sha1.New(), nil
case "sha256":
return sha256.New(), nil
case "sha512":
return sha512.New(), nil
default:
return nil, fmt.Errorf("unknown hash algorithm: %s", n)
}
}
func toEnc(n string) (hashEncoder, error) {
switch strings.ToLower(n) {
case "hex":
return hashEncHex, nil
case "base64":
return hashEncBase64, nil
case "binary":
return hashEncBin, nil
default:
return nil, fmt.Errorf("unknown hash encoder: %s", n)
}
}
func hashEncHex(w io.Writer, b []byte) error {
_, err := fmt.Fprintf(w, "%x", b)
return err
}
func hashEncBase64(w io.Writer, b []byte) error {
s := base64.StdEncoding.EncodeToString(b)
_, err := w.Write([]byte(s))
return err
}
func hashEncBin(w io.Writer, b []byte) error {
_, err := w.Write(b)
return err
}
func newHash(r *resource.Resource, p Params) (*resource.Resource, error) {
h, err := toHash(p.String("algorithm", "md5"))
if err != nil {
return nil, err
}
enc, err := toEnc(p.String("encoding", "hex"))
if err != nil {
return nil, err
}
return r.Wrap(NewHash(r, h, enc)), nil
}
func init() {
MustRegister("hash", newHash)
}