canonical_text.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. package openpgp
  5. import "hash"
  6. // NewCanonicalTextHash reformats text written to it into the canonical
  7. // form and then applies the hash h. See RFC 4880, section 5.2.1.
  8. func NewCanonicalTextHash(h hash.Hash) hash.Hash {
  9. return &canonicalTextHash{h, 0}
  10. }
  11. type canonicalTextHash struct {
  12. h hash.Hash
  13. s int
  14. }
  15. var newline = []byte{'\r', '\n'}
  16. func (cth *canonicalTextHash) Write(buf []byte) (int, error) {
  17. start := 0
  18. for i, c := range buf {
  19. switch cth.s {
  20. case 0:
  21. if c == '\r' {
  22. cth.s = 1
  23. } else if c == '\n' {
  24. cth.h.Write(buf[start:i])
  25. cth.h.Write(newline)
  26. start = i + 1
  27. }
  28. case 1:
  29. cth.s = 0
  30. }
  31. }
  32. cth.h.Write(buf[start:])
  33. return len(buf), nil
  34. }
  35. func (cth *canonicalTextHash) Sum(in []byte) []byte {
  36. return cth.h.Sum(in)
  37. }
  38. func (cth *canonicalTextHash) Reset() {
  39. cth.h.Reset()
  40. cth.s = 0
  41. }
  42. func (cth *canonicalTextHash) Size() int {
  43. return cth.h.Size()
  44. }
  45. func (cth *canonicalTextHash) BlockSize() int {
  46. return cth.h.BlockSize()
  47. }