以下是Golang中使用AESMode进行ECB加密和解密(不使用填充)的示例代码:
package main
import ( "crypto/aes" "crypto/cipher" "fmt" )
func PKCS7Padding(data []byte, blockSize int) []byte { padding := blockSize - len(data) % blockSize padtext := bytes.Repeat([]byte{byte(padding)}, padding) return append(data, padtext...) }
func PKCS7UnPadding(data []byte) []byte { length := len(data) unpadding := int(data[length-1]) return data[:(length - unpadding)] }
func AESEncrypt(rawData []byte, key []byte) []byte { block, _ := aes.NewCipher(key) mode := cipher.NewCBCEncrypter(block, key[:block.BlockSize()]) ciphertext := make([]byte, len(rawData)) mode.CryptBlocks(ciphertext, rawData) return ciphertext }
func AESDecrypt(ciphertext []byte, key []byte) []byte { block, _ := aes.NewCipher(key) mode := cipher.NewCBCDecrypter(block, key[:block.BlockSize()]) rawData := make([]byte, len(ciphertext)) mode.CryptBlocks(rawData, ciphertext) rawData = PKCS7UnPadding(rawData) return rawData }
func main() { key := []byte("0123456789abcdef") plaintext := []byte("exampleinputtext") ciphertext := AESEncrypt(PKCS7Padding(plaintext, aes.BlockSize), key) fmt.Printf("%x\n", ciphertext) rawData := AESDecrypt(ciphertext, key) fmt.Printf("%s\n", rawData) }
在此示例中,我们使用PKCS7填充和取消填充算法对原始文本进行填充和取消填充。我们还使用Crypto / Cipher包中的NewCBCEncrypter和NewCBCDecrypter函数将块加密和解密器与密钥和原始数据一起使用。