You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
lib/crypto/aes.go

48 lines
1.2 KiB
Go

package crypto
import (
"bytes"
"crypto/aes"
"crypto/cipher"
)
func paddingPKCS7(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
func unpaddingPKCS7(origData []byte) []byte {
length := len(origData)
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}
//EncryptAES 加密函式
func EncryptAES(plaintext, key, iv []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
plaintext = paddingPKCS7(plaintext, blockSize)
blockMode := cipher.NewCBCEncrypter(block, iv)
crypted := make([]byte, len(plaintext))
blockMode.CryptBlocks(crypted, plaintext)
return crypted, nil
}
// DecryptAES 解密函式
func DecryptAES(ciphertext, key, iv []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
blockMode := cipher.NewCBCDecrypter(block, iv[:blockSize])
origData := make([]byte, len(ciphertext))
blockMode.CryptBlocks(origData, ciphertext)
origData = unpaddingPKCS7(origData)
return origData, nil
}