| 114 | } |
| 115 | |
| 116 | func TestEncryptDecrypt(t *testing.T) { |
| 117 | // Declare the plaintext and the key. |
| 118 | m := make([]byte, 64) |
| 119 | Scramble(m) |
| 120 | k := make([]byte, 32) |
| 121 | Scramble(k) |
| 122 | |
| 123 | // Encrypt the message. |
| 124 | x, err := Encrypt(m, k) |
| 125 | if err != nil { |
| 126 | t.Error("expected no errors; got", err) |
| 127 | } |
| 128 | |
| 129 | // Decrypt the message. |
| 130 | dm := make([]byte, len(x)-Overhead) |
| 131 | length, err := Decrypt(x, k, dm) |
| 132 | if err != nil { |
| 133 | t.Error("expected no errors; got", err) |
| 134 | } |
| 135 | if length != len(x)-Overhead { |
| 136 | t.Error("unexpected plaintext length; got", length) |
| 137 | } |
| 138 | |
| 139 | // Verify that the plaintexts match. |
| 140 | if !bytes.Equal(m, dm) { |
| 141 | t.Error("decrypted plaintext does not match original") |
| 142 | } |
| 143 | |
| 144 | // Attempt decryption /w buffer that is too small to hold the output. |
| 145 | out := make([]byte, len(x)-Overhead-1) |
| 146 | length, err = Decrypt(x, k, out) |
| 147 | if err != ErrBufferTooSmall { |
| 148 | t.Error("expected error; got", err) |
| 149 | } |
| 150 | if length != 0 { |
| 151 | t.Error("expected zero length; got", length) |
| 152 | } |
| 153 | |
| 154 | // Construct a buffer that has the correct capacity but a smaller length. |
| 155 | out = make([]byte, len(x)-Overhead) |
| 156 | smallOut := out[:2] |
| 157 | if len(smallOut) != 2 || cap(smallOut) != len(x)-Overhead { |
| 158 | t.Error("invalid construction for test") |
| 159 | } |
| 160 | length, err = Decrypt(x, k, smallOut) |
| 161 | if err != nil { |
| 162 | t.Error("unexpected error:", err) |
| 163 | } |
| 164 | if length != len(x)-Overhead { |
| 165 | t.Error("unexpected length; got", length) |
| 166 | } |
| 167 | if !bytes.Equal(m, smallOut[:len(x)-Overhead]) { |
| 168 | t.Error("decrypted plaintext does not match original") |
| 169 | } |
| 170 | |
| 171 | // Generate an incorrect key. |
| 172 | ik := make([]byte, 32) |
| 173 | Scramble(ik) |