aes_encryption.go
1.2 KB
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
package socialwork_sdk
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
)
func aes_CBC_Decrypt(crypted []byte, key, iv []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockMode := cipher.NewCBCDecrypter(block, iv)
origData := make([]byte, len(crypted))
blockMode.CryptBlocks(origData, crypted)
origData = unpadding(origData)
return origData, nil
}
func unpadding(cipherText []byte) []byte {
end := cipherText[len(cipherText)-1]
cipherText = cipherText[:len(cipherText)-int(end)]
return cipherText
}
func aes_CBC_Encrypt(data []byte, key, iv []byte) (string, error) {
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
origData := padding([]byte(data), block.BlockSize())
println("block ", block.BlockSize())
println("block2 ", len(iv))
blockMode := cipher.NewCBCEncrypter(block, iv)
crypted := make([]byte, len(origData))
blockMode.CryptBlocks(crypted, origData)
return base64.StdEncoding.EncodeToString(crypted), nil
}
func padding(plainText []byte, blockSize int) []byte {
n := blockSize - len(plainText)%blockSize
temp := bytes.Repeat([]byte{byte(n)}, n)
plainText = append(plainText, temp...)
return plainText
}