github.com/qxnw/lib4go@v0.0.0-20180426074627-c80c7e84b925/security/aes/aes.cbc.go (about)

     1  package aes
     2  
     3  import (
     4  	"crypto/aes"
     5  	"crypto/cipher"
     6  	"fmt"
     7  
     8  	"github.com/qxnw/lib4go/encoding/base64"
     9  	"github.com/qxnw/lib4go/security/des"
    10  )
    11  
    12  // EncryptCBCPKCS7WithIV CBC模式,PKCS7填充
    13  func EncryptCBCPKCS7WithIV(contentStr string, keyStr string, iv []byte) (string, error) {
    14  	content := []byte(contentStr)
    15  	key := []byte(keyStr)
    16  
    17  	block, err := aes.NewCipher(key)
    18  	if err != nil {
    19  		return "", err
    20  	}
    21  
    22  	content = des.PKCS7Padding(content)
    23  	if iv == nil {
    24  		iv = make([]byte, block.BlockSize())
    25  	}
    26  	blockModel := cipher.NewCBCEncrypter(block, iv)
    27  
    28  	cipherText := make([]byte, len(content))
    29  	blockModel.CryptBlocks(cipherText, content)
    30  	return base64.EncodeBytes(cipherText), nil
    31  }
    32  
    33  // DecryptCBCPKCS7WithIV CBC模式,PKCS7填充
    34  func DecryptCBCPKCS7WithIV(contentStr string, keyStr string, iv []byte) (string, error) {
    35  	content, err := base64.DecodeBytes(contentStr)
    36  	if err != nil {
    37  		return "", err
    38  	}
    39  
    40  	key := []byte(keyStr)
    41  	block, err := aes.NewCipher(key)
    42  	if err != nil {
    43  		return "", err
    44  	}
    45  
    46  	if len(content) < aes.BlockSize {
    47  		return "", fmt.Errorf("要解密的字符串太短")
    48  	}
    49  	if iv == nil {
    50  		iv = make([]byte, block.BlockSize())
    51  	}
    52  	blockModel := cipher.NewCBCDecrypter(block, iv)
    53  
    54  	plantText := make([]byte, len(content))
    55  	blockModel.CryptBlocks(plantText, content)
    56  	plantText = des.PKCS7UnPadding(plantText)
    57  	return string(plantText), nil
    58  }