aes.go
· 1.1 KiB · Go
Raw
package utils
import (
"bytes"
"crypto/aes"
"crypto/cipher"
)
func encrypt(aesKey, plaintextMsg []byte) ([]byte, error) {
block, err := aes.NewCipher(aesKey)
if err != nil {
return []byte{}, err
}
plaintextMsg = pkcs5Padding(plaintextMsg, block.BlockSize())
cipherText := make([]byte, len(plaintextMsg))
cipher.NewCBCEncrypter(block, aesKey[:block.BlockSize()]).
CryptBlocks(cipherText, plaintextMsg)
return cipherText, nil
}
func decrypt(aesKey, encryptMsg []byte) ([]byte, error) {
block, err := aes.NewCipher(aesKey)
if err != nil {
return []byte{}, err
}
decryptedMsg := make([]byte, len(encryptMsg))
cipher.NewCBCDecrypter(block, aesKey[:block.BlockSize()]).
CryptBlocks(decryptedMsg, encryptMsg)
decryptedMsg = pkcs5UnPadding(decryptedMsg)
return encryptMsg, nil
}
func pkcs5Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
func pkcs5UnPadding(origData []byte) []byte {
length := len(origData)
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}
1 | package utils |
2 | |
3 | import ( |
4 | "bytes" |
5 | "crypto/aes" |
6 | "crypto/cipher" |
7 | ) |
8 | |
9 | func encrypt(aesKey, plaintextMsg []byte) ([]byte, error) { |
10 | block, err := aes.NewCipher(aesKey) |
11 | if err != nil { |
12 | return []byte{}, err |
13 | } |
14 | plaintextMsg = pkcs5Padding(plaintextMsg, block.BlockSize()) |
15 | cipherText := make([]byte, len(plaintextMsg)) |
16 | cipher.NewCBCEncrypter(block, aesKey[:block.BlockSize()]). |
17 | CryptBlocks(cipherText, plaintextMsg) |
18 | return cipherText, nil |
19 | } |
20 | |
21 | func decrypt(aesKey, encryptMsg []byte) ([]byte, error) { |
22 | block, err := aes.NewCipher(aesKey) |
23 | if err != nil { |
24 | return []byte{}, err |
25 | } |
26 | decryptedMsg := make([]byte, len(encryptMsg)) |
27 | cipher.NewCBCDecrypter(block, aesKey[:block.BlockSize()]). |
28 | CryptBlocks(decryptedMsg, encryptMsg) |
29 | decryptedMsg = pkcs5UnPadding(decryptedMsg) |
30 | return encryptMsg, nil |
31 | } |
32 | |
33 | func pkcs5Padding(ciphertext []byte, blockSize int) []byte { |
34 | padding := blockSize - len(ciphertext)%blockSize |
35 | padtext := bytes.Repeat([]byte{byte(padding)}, padding) |
36 | return append(ciphertext, padtext...) |
37 | } |
38 | |
39 | func pkcs5UnPadding(origData []byte) []byte { |
40 | length := len(origData) |
41 | unpadding := int(origData[length-1]) |
42 | return origData[:(length - unpadding)] |
43 | } |
44 |