github.com/godaddy-x/freego@v1.0.156/utils/crypto_aes.go (about)

     1  package utils
     2  
     3  import (
     4  	"bytes"
     5  	"crypto/aes"
     6  	"crypto/cipher"
     7  	"errors"
     8  )
     9  
    10  func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
    11  	padding := blockSize - len(ciphertext)%blockSize
    12  	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
    13  	return append(ciphertext, padtext...)
    14  }
    15  
    16  func PKCS7UnPadding(plantText []byte, blockSize int) []byte {
    17  	if plantText == nil || len(plantText) == 0 {
    18  		return nil
    19  	}
    20  	length := len(plantText)
    21  	unpadding := int(plantText[length-1])
    22  	if length-unpadding <= 0 {
    23  		return nil
    24  	}
    25  	return plantText[:(length - unpadding)]
    26  }
    27  
    28  func AesEncrypt(plantText []byte, key, iv string) (string, error) {
    29  	block, err := aes.NewCipher(GetAesKey(key)) //选择加密算法
    30  	if err != nil {
    31  		return "", err
    32  	}
    33  	plantText = PKCS7Padding(plantText, block.BlockSize())
    34  	blockModel := cipher.NewCBCEncrypter(block, GetAesIV(iv))
    35  	ciphertext := make([]byte, len(plantText))
    36  	blockModel.CryptBlocks(ciphertext, plantText)
    37  	return Base64Encode(ciphertext), nil
    38  }
    39  
    40  func AesDecrypt(msg, key, iv string) ([]byte, error) {
    41  	block, err := aes.NewCipher(GetAesKey(key)) //选择加密算法
    42  	if err != nil {
    43  		return nil, err
    44  	}
    45  	ciphertext := Base64Decode(msg)
    46  	if ciphertext == nil || len(ciphertext) == 0 {
    47  		return nil, err
    48  	}
    49  	blockModel := cipher.NewCBCDecrypter(block, GetAesIV(iv))
    50  	plantText := make([]byte, len(ciphertext))
    51  	blockModel.CryptBlocks(plantText, ciphertext)
    52  	plantText = PKCS7UnPadding(plantText, block.BlockSize())
    53  	if plantText == nil {
    54  		return nil, errors.New("unPadding data failed")
    55  	}
    56  	return plantText, nil
    57  }
    58  
    59  func GetAesKey(key string) []byte {
    60  	return Str2Bytes(MD5(key))
    61  }
    62  
    63  func GetAesIV(iv string) []byte {
    64  	return Str2Bytes(Substr(MD5(iv), 0, 16))
    65  }