main
1// Copyright 2011 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package openpgp
6
7import (
8 "hash"
9 "io"
10)
11
12// NewCanonicalTextHash reformats text written to it into the canonical
13// form and then applies the hash h. See RFC 4880, section 5.2.1.
14func NewCanonicalTextHash(h hash.Hash) hash.Hash {
15 return &canonicalTextHash{h, 0}
16}
17
18type canonicalTextHash struct {
19 h hash.Hash
20 s int
21}
22
23var newline = []byte{'\r', '\n'}
24
25func writeCanonical(cw io.Writer, buf []byte, s *int) (int, error) {
26 start := 0
27 for i, c := range buf {
28 switch *s {
29 case 0:
30 if c == '\r' {
31 *s = 1
32 } else if c == '\n' {
33 if _, err := cw.Write(buf[start:i]); err != nil {
34 return 0, err
35 }
36 if _, err := cw.Write(newline); err != nil {
37 return 0, err
38 }
39 start = i + 1
40 }
41 case 1:
42 *s = 0
43 }
44 }
45
46 if _, err := cw.Write(buf[start:]); err != nil {
47 return 0, err
48 }
49 return len(buf), nil
50}
51
52func (cth *canonicalTextHash) Write(buf []byte) (int, error) {
53 return writeCanonical(cth.h, buf, &cth.s)
54}
55
56func (cth *canonicalTextHash) Sum(in []byte) []byte {
57 return cth.h.Sum(in)
58}
59
60func (cth *canonicalTextHash) Reset() {
61 cth.h.Reset()
62 cth.s = 0
63}
64
65func (cth *canonicalTextHash) Size() int {
66 return cth.h.Size()
67}
68
69func (cth *canonicalTextHash) BlockSize() int {
70 return cth.h.BlockSize()
71}