-
Notifications
You must be signed in to change notification settings - Fork 0
/
aes.go
104 lines (78 loc) · 2.46 KB
/
aes.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
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"fmt"
"io"
)
func decrypt(cipherstring []byte, keystring string) string {
// Byte array of the string
ciphertext := []byte(cipherstring)
// Key
key := []byte(keystring)
// Create the AES cipher
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
// Before even testing the decryption,
// if the text is too small, then it is incorrect
if len(ciphertext) < aes.BlockSize {
panic("Text is too short")
}
// Get the 16 byte IV
iv := ciphertext[:aes.BlockSize]
// Remove the IV from the ciphertext
ciphertext = ciphertext[aes.BlockSize:]
// Return a decrypted stream
stream := cipher.NewCFBDecrypter(block, iv)
// Decrypt bytes from ciphertext
stream.XORKeyStream(ciphertext, ciphertext)
return string(ciphertext)
}
func encrypt(plainstring, keystring string) []byte {
// Byte array of the string
plaintext := []byte(plainstring)
// Key
key := []byte(keystring)
// Create the AES cipher
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
// Empty array of 16 + plaintext length
// Include the IV at the beginning
ciphertext := make([]byte, aes.BlockSize+len(plaintext))
// Slice of first 16 bytes
iv := ciphertext[:aes.BlockSize]
// Write 16 rand bytes to fill iv
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
panic(err)
}
// Return an encrypted stream
stream := cipher.NewCFBEncrypter(block, iv)
// Encrypt bytes from plaintext to ciphertext
stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
return ciphertext
}
func main() {
key := "abcdefghijklmnopqrstuvwxyz123456"
txt := `Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.`
x := encrypt(txt, key)
// the encrypted text isn't simple text... convert to base64
str := base64.StdEncoding.EncodeToString(x)
// now convert base64 back to byte
data, err := base64.StdEncoding.DecodeString(str)
if err != nil {
fmt.Println("error:", err)
return
}
y := decrypt(data, key)
if y != txt {
fmt.Println("Error! does not match")
} else {
fmt.Println("OK!")
}
}