Go 语言 AES 加密:`crypto/cipher` 包中的`input not full blocks` 错误解决方法
在使用 Go 语言的 crypto/cipher 包中的 AES 加密算法时,输入数据需要填充至块大小的倍数(通常对于 AES 为 16 字节)。
如果在使用 AES 加密时遇到错误消息“input not full blocks”,则表示您尝试加密的输入数据不是块大小的倍数。AES 加密需要输入数据为完整的块或块大小的倍数才能正常工作。
为了解决此错误,您需要使用额外的字节填充您的输入数据,使其成为块大小的倍数。有多种填充方案可用,例如 PKCS7 或 ZeroPadding。
以下是使用 PKCS7 填充方案填充输入数据的示例:
import (
"crypto/aes"
"crypto/cipher"
"bytes"
"fmt"
)
func encryptWithAES(key, plaintext []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
plaintext = PKCS7Padding(plaintext, blockSize)
ciphertext := make([]byte, len(plaintext))
iv := make([]byte, blockSize)
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(ciphertext, plaintext)
return ciphertext, nil
}
func PKCS7Padding(data []byte, blockSize int) []byte {
padding := blockSize - len(data)%blockSize
padText := bytes.Repeat([]byte{byte(padding)}, padding)
return append(data, padText...)
}
func main() {
key := []byte("0123456789abcdef")
plaintext := []byte("Hello, World!")
ciphertext, err := encryptWithAES(key, plaintext)
if err != nil {
fmt.Println("Encryption error:", err)
return
}
fmt.Printf("Ciphertext: %x\n", ciphertext)
}
在此示例中,encryptWithAES 函数使用给定的 key 使用 AES 对 plaintext 进行加密。在加密之前,plaintext 使用 PKCS7Padding 函数使用 PKCS7 填充进行填充。
请确保在您的用例中使用合适的填充方案,并根据需要调整代码。
原文地址: https://www.cveoy.top/t/topic/pkhZ 著作权归作者所有。请勿转载和采集!