...
1
2
3
4
5 package packet
6
7 import (
8 "bytes"
9 "crypto/sha1"
10 "encoding/hex"
11 "golang.org/x/crypto/openpgp/errors"
12 "io"
13 "testing"
14 )
15
16
17 type testReader struct {
18 data []byte
19 stride int
20 }
21
22 func (t *testReader) Read(buf []byte) (n int, err error) {
23 n = t.stride
24 if n > len(t.data) {
25 n = len(t.data)
26 }
27 if n > len(buf) {
28 n = len(buf)
29 }
30 copy(buf, t.data)
31 t.data = t.data[n:]
32 if len(t.data) == 0 {
33 err = io.EOF
34 }
35 return
36 }
37
38 func testMDCReader(t *testing.T) {
39 mdcPlaintext, _ := hex.DecodeString(mdcPlaintextHex)
40
41 for stride := 1; stride < len(mdcPlaintext)/2; stride++ {
42 r := &testReader{data: mdcPlaintext, stride: stride}
43 mdcReader := &seMDCReader{in: r, h: sha1.New()}
44 body, err := io.ReadAll(mdcReader)
45 if err != nil {
46 t.Errorf("stride: %d, error: %s", stride, err)
47 continue
48 }
49 if !bytes.Equal(body, mdcPlaintext[:len(mdcPlaintext)-22]) {
50 t.Errorf("stride: %d: bad contents %x", stride, body)
51 continue
52 }
53
54 err = mdcReader.Close()
55 if err != nil {
56 t.Errorf("stride: %d, error on Close: %s", stride, err)
57 }
58 }
59
60 mdcPlaintext[15] ^= 80
61
62 r := &testReader{data: mdcPlaintext, stride: 2}
63 mdcReader := &seMDCReader{in: r, h: sha1.New()}
64 _, err := io.ReadAll(mdcReader)
65 if err != nil {
66 t.Errorf("corruption test, error: %s", err)
67 return
68 }
69 err = mdcReader.Close()
70 if err == nil {
71 t.Error("corruption: no error")
72 } else if _, ok := err.(*errors.SignatureError); !ok {
73 t.Errorf("corruption: expected SignatureError, got: %s", err)
74 }
75 }
76
77 const mdcPlaintextHex = "a302789c3b2d93c4e0eb9aba22283539b3203335af44a134afb800c849cb4c4de10200aff40b45d31432c80cb384299a0655966d6939dfdeed1dddf980"
78
79 func TestSerialize(t *testing.T) {
80 buf := bytes.NewBuffer(nil)
81 c := CipherAES128
82 key := make([]byte, c.KeySize())
83
84 w, err := SerializeSymmetricallyEncrypted(buf, c, key, nil)
85 if err != nil {
86 t.Errorf("error from SerializeSymmetricallyEncrypted: %s", err)
87 return
88 }
89
90 contents := []byte("hello world\n")
91
92 w.Write(contents)
93 w.Close()
94
95 p, err := Read(buf)
96 if err != nil {
97 t.Errorf("error from Read: %s", err)
98 return
99 }
100
101 se, ok := p.(*SymmetricallyEncrypted)
102 if !ok {
103 t.Errorf("didn't read a *SymmetricallyEncrypted")
104 return
105 }
106
107 r, err := se.Decrypt(c, key)
108 if err != nil {
109 t.Errorf("error from Decrypt: %s", err)
110 return
111 }
112
113 contentsCopy := bytes.NewBuffer(nil)
114 _, err = io.Copy(contentsCopy, r)
115 if err != nil {
116 t.Errorf("error from io.Copy: %s", err)
117 return
118 }
119 if !bytes.Equal(contentsCopy.Bytes(), contents) {
120 t.Errorf("contents not equal got: %x want: %x", contentsCopy.Bytes(), contents)
121 }
122 }
123
View as plain text