/
checksum.go
86 lines (76 loc) · 1.53 KB
/
checksum.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
//
// checksum.go
//
// Created by Frederic DELBOS - fred@hyperboloide.com on Feb 10 2015.
// This file is subject to the terms and conditions defined in
// file 'LICENSE', which is part of this source code package.
//
package sprocess
import (
"crypto/md5"
"crypto/sha1"
"errors"
"fmt"
"hash"
"io"
)
type CheckSum struct {
Hash string
Name string
}
func (c *CheckSum) GetName() string {
return c.Name
}
func (c *CheckSum) Start() error {
switch c.Hash {
case "", "md5", "sha1":
default:
return errors.New("Hash '" + c.Hash + "' is not supported")
}
if c.Name == "" {
return errors.New("Checksum must have a name")
}
return nil
}
func (c *CheckSum) Encode(r io.Reader, w io.Writer, d *Data) error {
var h hash.Hash
switch c.Hash {
case "", "sha1":
h = sha1.New()
case "md5":
h = md5.New()
default:
return errors.New("Hash '" + c.Hash + "' is not supported")
}
reader := io.TeeReader(r, h)
_, err := io.Copy(w, reader)
if err != nil {
return err
}
d.Set(c.GetName(), fmt.Sprintf("%x", h.Sum(nil)))
return nil
}
func (c *CheckSum) Decode(r io.Reader, w io.Writer, d *Data) error {
var h hash.Hash
switch c.Hash {
case "", "sha1":
h = sha1.New()
case "md5":
h = md5.New()
default:
return errors.New("Hash '" + c.Hash + "' is not supported")
}
value, err := d.Get(c.GetName())
if err != nil {
return err
}
reader := io.TeeReader(r, h)
_, err = io.Copy(w, reader)
if err != nil {
return err
}
if fmt.Sprintf("%x", h.Sum(nil)) != value {
return errors.New("CheckSums do not match")
}
return nil
}