github.com/tickstep/library-go@v0.1.1/crypto/aes.go (about) 1 package crypto 2 3 import ( 4 "bytes" 5 "crypto/aes" 6 "crypto/cipher" 7 ) 8 9 // 填充数据 10 func padding(src []byte, blockSize int) []byte { 11 padNum := blockSize - len(src) % blockSize 12 pad := bytes.Repeat([]byte{byte(padNum)}, padNum) 13 return append(src, pad...) 14 } 15 16 // 去掉填充数据 17 func unpadding(src []byte) []byte { 18 n := len(src) 19 unPadNum := int(src[n-1]) 20 return src[:n-unPadNum] 21 } 22 23 // 加密 24 func EncryptAES(src []byte, key []byte) ([]byte, error) { 25 block, err := aes.NewCipher(key) 26 if err != nil { 27 return nil, err 28 } 29 src = padding(src, block.BlockSize()) 30 blockMode := cipher.NewCBCEncrypter(block, key) 31 blockMode.CryptBlocks(src, src) 32 return src, nil 33 } 34 35 // 解密 36 func DecryptAES(src []byte, key []byte) ([]byte, error) { 37 block, err := aes.NewCipher(key) 38 if err != nil { 39 return nil, err 40 } 41 blockMode := cipher.NewCBCDecrypter(block, key) 42 blockMode.CryptBlocks(src, src) 43 src = unpadding(src) 44 return src, nil 45 }