-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrypt.go
126 lines (93 loc) · 2.31 KB
/
crypt.go
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package cryptanalysis
import (
"crypto/aes"
"errors"
)
const block_size = 16
func EncryptXor(plain, key []byte) []byte {
var cipher []byte
for i := 0; i < len(plain); i++ {
e := plain[i] ^ key[i%len(key)]
cipher = append(cipher, e)
}
return cipher
}
func EncryptEcb(plaintext, key []byte) ([]byte, error) {
ciphertext := make([]byte, 0)
plaintext = PadPkcs7(plaintext, block_size)
chunks := Chunk(plaintext, block_size)
ecb, err := aes.NewCipher(key)
if err != nil {
return ciphertext, err
}
for _, chunk := range chunks {
temp := make([]byte, block_size)
ecb.Encrypt(temp, chunk)
ciphertext = append(ciphertext, temp...)
}
return ciphertext, nil
}
func DecryptEcb(ciphertext, key []byte) ([]byte, error) {
plaintext := make([]byte, 0)
if len(ciphertext)%block_size != 0 {
return plaintext, errors.New("Ciphertext is not padded properly.")
}
chunks := Chunk(ciphertext, block_size)
ecb, err := aes.NewCipher(key)
if err != nil {
return plaintext, err
}
for _, chunk := range chunks {
temp := make([]byte, block_size)
ecb.Decrypt(temp, chunk)
plaintext = append(plaintext, temp...)
}
return plaintext, nil
}
func EncryptCbc(plaintext, key, iv []byte) ([]byte, error) {
null := make([]byte, 0)
ciphertext := make([]byte, 0)
plaintext = PadPkcs7(plaintext, block_size)
if len(iv) != block_size {
return null, errors.New("IV must be 16 bytes long.")
}
cbc, err := aes.NewCipher(key)
if err != nil {
return null, err
}
chunks := Chunk(plaintext, block_size)
for _, chunk := range chunks {
temp := make([]byte, block_size)
chunk, err = XorArrays(chunk, iv)
if err != nil {
return null, err
}
cbc.Encrypt(temp, chunk)
iv = temp
ciphertext = append(ciphertext, temp...)
}
return ciphertext, nil
}
func DecryptCbc(ciphertext, key, iv []byte) ([]byte, error) {
null := make([]byte, 0)
plaintext := make([]byte, 0)
if len(iv) != block_size {
return null, errors.New("IV must be 16 bytes long.")
}
cbc, err := aes.NewCipher(key)
if err != nil {
return null, err
}
chunks := Chunk(ciphertext, block_size)
for _, chunk := range chunks {
temp := make([]byte, block_size)
cbc.Decrypt(temp, chunk)
temp, err = XorArrays(temp, iv)
if err != nil {
return null, err
}
iv = chunk
plaintext = append(plaintext, temp...)
}
return plaintext, nil
}