github.com/johnnyeven/libtools@v0.0.0-20191126065708-61829c1adf46/crypto/aes_ecb/aes_ecb.go (about)

     1  package aes_ecb
     2  
     3  import (
     4  	"crypto/aes"
     5  	"bytes"
     6  )
     7  
     8  /*
     9  	加密模式:ECB
    10  	填充方式:pkcs7 padding
    11  	字符集:utf-8
    12  
    13  e.g.
    14  	加密前字符:abcdef
    15  	密钥Skey:1234567890123456
    16  	加密后字符:Z/olGq/NuDT3W8pGNh/DHg==
    17   */
    18  
    19  //AES ECB模式的加密解密
    20  type AesTool struct {
    21  	//128 192  256位的其中一个 长度 对应分别是 16 24  32字节长度
    22  	Key       []byte
    23  	BlockSize int
    24  }
    25  
    26  func NewAesTool(key []byte, blockSize int) *AesTool {
    27  	return &AesTool{Key: key, BlockSize: blockSize}
    28  }
    29  
    30  func (this *AesTool) padding(src []byte) []byte {
    31  	//填充个数
    32  	paddingCount := aes.BlockSize - len(src)%aes.BlockSize
    33  	if paddingCount == 0 {
    34  		return src
    35  	} else {
    36  		//填充数据
    37  		return append(src, bytes.Repeat([]byte{byte(0)}, paddingCount)...)
    38  	}
    39  }
    40  
    41  //unpadding
    42  func (this *AesTool) unPadding(src []byte) []byte {
    43  	for i := len(src) - 1; ; i-- {
    44  		if src[i] != 0 {
    45  			return src[:i+1]
    46  		}
    47  	}
    48  	return nil
    49  }
    50  
    51  func (this *AesTool) Encrypt(src []byte) ([]byte, error) {
    52  	//key只能是 16 24 32长度
    53  	block, err := aes.NewCipher([]byte(this.Key))
    54  	if err != nil {
    55  		return nil, err
    56  	}
    57  	//padding
    58  	src = this.padding(src)
    59  	//返回加密结果
    60  	encryptData := make([]byte, len(src))
    61  	//存储每次加密的数据
    62  	tmpData := make([]byte, this.BlockSize)
    63  
    64  	//分组分块加密
    65  	for index := 0; index < len(src); index += this.BlockSize {
    66  		block.Encrypt(tmpData, src[index:index+this.BlockSize])
    67  		copy(encryptData, tmpData)
    68  	}
    69  	return encryptData, nil
    70  }
    71  func (this *AesTool) Decrypt(src []byte) ([]byte, error) {
    72  	//key只能是 16 24 32长度
    73  	block, err := aes.NewCipher([]byte(this.Key))
    74  	if err != nil {
    75  		return nil, err
    76  	}
    77  	//返回加密结果
    78  	decryptData := make([]byte, len(src))
    79  	//存储每次加密的数据
    80  	tmpData := make([]byte, this.BlockSize)
    81  
    82  	//分组分块加密
    83  	for index := 0; index < len(src); index += this.BlockSize {
    84  		block.Decrypt(tmpData, src[index:index+this.BlockSize])
    85  		copy(decryptData, tmpData)
    86  	}
    87  	return this.unPadding(decryptData), nil
    88  }