File: aes_test.go

package info (click to toggle)
golang-github-coreos-pkg 2-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 304 kB
  • ctags: 244
  • sloc: sh: 30; makefile: 3
file content (93 lines) | stat: -rw-r--r-- 2,196 bytes parent folder | download | duplicates (3)
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
87
88
89
90
91
92
93
package cryptoutil

import (
	"reflect"
	"testing"
)

func TestPadUnpad(t *testing.T) {
	tests := []struct {
		plaintext []byte
		bsize     int
		padded    []byte
	}{
		{
			plaintext: []byte{1, 2, 3, 4},
			bsize:     7,
			padded:    []byte{1, 2, 3, 4, 3, 3, 3},
		},
		{
			plaintext: []byte{1, 2, 3, 4, 5, 6, 7},
			bsize:     3,
			padded:    []byte{1, 2, 3, 4, 5, 6, 7, 2, 2},
		},
		{
			plaintext: []byte{9, 9, 9, 9},
			bsize:     4,
			padded:    []byte{9, 9, 9, 9, 4, 4, 4, 4},
		},
	}

	for i, tt := range tests {
		padded, err := pad(tt.plaintext, tt.bsize)
		if err != nil {
			t.Errorf("case %d: unexpected error: %v", i, err)
			continue
		}
		if !reflect.DeepEqual(tt.padded, padded) {
			t.Errorf("case %d: want=%v got=%v", i, tt.padded, padded)
			continue
		}

		plaintext, err := unpad(tt.padded)
		if err != nil {
			t.Errorf("case %d: unexpected error: %v", i, err)
			continue
		}
		if !reflect.DeepEqual(tt.plaintext, plaintext) {
			t.Errorf("case %d: want=%v got=%v", i, tt.plaintext, plaintext)
			continue
		}
	}
}

func TestPadMaxBlockSize(t *testing.T) {
	_, err := pad([]byte{1, 2, 3}, 256)
	if err == nil {
		t.Errorf("Expected non-nil error")
	}
}

func TestAESEncryptDecrypt(t *testing.T) {
	message := []byte("Let me worry about blank.")
	key := append([]byte("shark"), make([]byte, 27)...)

	ciphertext, err := AESEncrypt(message, key)
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}
	if reflect.DeepEqual(message, ciphertext) {
		t.Fatal("Encrypted data matches original payload")
	}

	decrypted, err := AESDecrypt(ciphertext, key)
	if !reflect.DeepEqual(message, decrypted) {
		t.Fatalf("Decrypted data does not match original payload: want=%v got=%v", message, decrypted)
	}
}

func TestAESDecryptWrongKey(t *testing.T) {
	message := []byte("My bones!")
	key := append([]byte("shark"), make([]byte, 27)...)

	ciphertext, err := AESEncrypt(message, key)
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}

	wrongKey := append([]byte("sheep"), make([]byte, 27)...)
	decrypted, _ := AESDecrypt(ciphertext, wrongKey)
	if reflect.DeepEqual(message, decrypted) {
		t.Fatalf("Data decrypted with different key matches original payload")
	}
}