|
@@ -4,42 +4,53 @@ import (
|
|
|
"bytes"
|
|
|
"crypto/aes"
|
|
|
"crypto/cipher"
|
|
|
+ "fmt"
|
|
|
)
|
|
|
|
|
|
func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
|
|
|
- padding := blockSize - len(ciphertext)%blockSize
|
|
|
- padtext := bytes.Repeat([]byte{byte(padding)}, padding)
|
|
|
- return append(ciphertext, padtext...)
|
|
|
+ m := blockSize - len(ciphertext)%blockSize
|
|
|
+ n := bytes.Repeat([]byte{byte(m)}, m)
|
|
|
+ return append(ciphertext, n...)
|
|
|
}
|
|
|
|
|
|
func PKCS7UnPadding(origData []byte) []byte {
|
|
|
- length := len(origData)
|
|
|
- unpadding := int(origData[length-1])
|
|
|
- return origData[:(length - unpadding)]
|
|
|
+ m := len(origData)
|
|
|
+ n := int(origData[m-1])
|
|
|
+ return origData[:(m - n)]
|
|
|
}
|
|
|
|
|
|
-func AesEncrypt(origData, key []byte) ([]byte, error) {
|
|
|
+func AesEncrypt(buf, key []byte) ([]byte, error) {
|
|
|
block, err := aes.NewCipher(key)
|
|
|
if err != nil {
|
|
|
return nil, err
|
|
|
}
|
|
|
+ defer func() {
|
|
|
+ if v := recover(); v != nil {
|
|
|
+ err = fmt.Errorf("decrypt error %v", v)
|
|
|
+ }
|
|
|
+ }()
|
|
|
blockSize := block.BlockSize()
|
|
|
- origData = PKCS7Padding(origData, blockSize)
|
|
|
+ buf = PKCS7Padding(buf, blockSize)
|
|
|
blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
|
|
|
- crypted := make([]byte, len(origData))
|
|
|
- blockMode.CryptBlocks(crypted, origData)
|
|
|
- return crypted, nil
|
|
|
+ tmp := make([]byte, len(buf))
|
|
|
+ blockMode.CryptBlocks(tmp, buf)
|
|
|
+ return tmp, nil
|
|
|
}
|
|
|
|
|
|
-func AesDecrypt(crypted, key []byte) ([]byte, error) {
|
|
|
+func AesDecrypt(buf, key []byte) ([]byte, error) {
|
|
|
block, err := aes.NewCipher(key)
|
|
|
if err != nil {
|
|
|
return nil, err
|
|
|
}
|
|
|
+ defer func() {
|
|
|
+ if v := recover(); v != nil {
|
|
|
+ err = fmt.Errorf("decrypt error %v", v)
|
|
|
+ }
|
|
|
+ }()
|
|
|
blockSize := block.BlockSize()
|
|
|
blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
|
|
|
- origData := make([]byte, len(crypted))
|
|
|
- blockMode.CryptBlocks(origData, crypted)
|
|
|
+ origData := make([]byte, len(buf))
|
|
|
+ blockMode.CryptBlocks(origData, buf)
|
|
|
origData = PKCS7UnPadding(origData)
|
|
|
return origData, nil
|
|
|
}
|