-
Notifications
You must be signed in to change notification settings - Fork 2
/
aes-256.go
75 lines (56 loc) · 1.53 KB
/
aes-256.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
// my-go-examples aes.go
package main
import (
"crypto/aes"
"encoding/hex"
"fmt"
"log"
)
func checkErr(err error) {
if err != nil {
fmt.Printf("Error is %+v\n", err)
log.Fatal("ERROR:", err)
}
}
func encrypt(keyByte []byte, plaintext string) string {
// WILL ONLY ENCRYPT 16 BYTES (128 bits)
plaintextByte := []byte(plaintext)
cipherTextByte := make([]byte, 16)
// GET CIPHER BLOCK USING KEY
block, err := aes.NewCipher(keyByte)
checkErr(err)
// ENCRYPT DATA
block.Encrypt(cipherTextByte, plaintextByte)
// RETURN HEX
cipherText := hex.EncodeToString(cipherTextByte)
return cipherText
}
func decrypt(keyByte []byte, cipherText string) string {
// IT IS 16 BYTES (128 bits)
cipherTextByte, _ := hex.DecodeString(cipherText)
plainTextByte := make([]byte, 16)
// GET CIPHER BLOCK USING KEY
block, err := aes.NewCipher(keyByte)
checkErr(err)
// DECRYPT DATA
block.Decrypt(plainTextByte, cipherTextByte)
// RETURN STRING
plainText := string(plainTextByte[:])
return plainText
}
func main() {
// DATA
// Must be at least 16 bytes
plainText := "Hello Jeff, only 16 Bytes of this will be encrypted."
fmt.Printf("\nOriginal Text: %s\n\n", plainText)
// KEY
keyText := "myverystrongpasswordo32bitlength"
keyByte := []byte(keyText)
fmt.Printf("The 32-byte Key: %s\n\n", keyText)
// ENCRYPT
cipherText := encrypt(keyByte, plainText)
fmt.Printf("Encrypted Text: %s\n", cipherText)
// DECRYPT
plainText = decrypt(keyByte, cipherText)
fmt.Printf("Decrypted Text: %s\n\n", plainText)
}