-
Notifications
You must be signed in to change notification settings - Fork 0
/
encryptAES.go
37 lines (29 loc) · 853 Bytes
/
encryptAES.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
package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
)
func encryptAES(input, key string) string {
// Convert key to []byte
keyBytes := []byte(key)
// Create AES block
block, err := aes.NewCipher(keyBytes)
if err != nil {
return ""
}
// Add padding to the input text, if necessary
inputBytes := []byte(input)
padding := aes.BlockSize - len(inputBytes)%aes.BlockSize
paddingText := bytes.Repeat([]byte{byte(padding)}, padding)
inputBytes = append(inputBytes, paddingText...)
// We create the cipher block
mode := cipher.NewCBCEncrypter(block, keyBytes[:aes.BlockSize])
// Encrypt the input text
ciphertext := make([]byte, len(inputBytes))
mode.CryptBlocks(ciphertext, inputBytes)
// Encode the result in base64
encryptedText := base64.StdEncoding.EncodeToString(ciphertext)
return encryptedText
}