/
crypt.go
53 lines (48 loc) · 1.28 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
package utils
import (
"bytes"
"crypto/aes"
"crypto/cipher"
)
// AES128Encrypt AES-128 encrypt
func AES128Encrypt(origData, key, iv []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
if len(iv) == 0 {
iv = key
}
origData = pkcs5Padding(origData, blockSize)
blockMode := cipher.NewCBCEncrypter(block, iv[:blockSize])
crypted := make([]byte, len(origData))
blockMode.CryptBlocks(crypted, origData)
return crypted, nil
}
// AES128Decrypt AES-128 decrypt
func AES128Decrypt(crypted, key, iv []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
if len(iv) == 0 {
iv = key
}
blockMode := cipher.NewCBCDecrypter(block, iv[:blockSize])
origData := make([]byte, len(crypted))
blockMode.CryptBlocks(origData, crypted)
origData = pkcs5UnPadding(origData)
return origData, 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)]
}