‘Go 语言 AES 加密 crypto/cipher: input not full blocks’ 是一个常见的错误信息,表示加密函数接收到的输入数据长度不是一个完整的块。

在 AES 加密算法中,数据通常被分成固定长度的块进行加密。如果输入数据的长度不是块长度的倍数,加密函数就会报错。

要解决这个问题,可以使用填充方法将输入数据填充到块长度的倍数。常用的填充方法有 PKCS7 和 ZeroPadding。具体的填充方法取决于你的需求和使用的 AES 加密库。

以下是一个示例代码,演示如何使用 PKCS7 填充方法将输入数据填充到块长度的倍数:

package main

import (
	"crypto/aes"
	"crypto/cipher"
	"fmt"
	"bytes"
)

func main() {
	key := []byte("0123456789ABCDEF")
	plaintext := []byte("Hello World")

	// 创建 AES 加密算法的块
	block, err := aes.NewCipher(key)
	if err != nil {
		fmt.Println(err)
		return
	}

	// 使用 PKCS7 填充方法将输入数据填充到块长度的倍数
	padding := aes.BlockSize - len(plaintext)%aes.BlockSize
	paddedPlaintext := append(plaintext, bytes.Repeat([]byte{byte(padding)}, padding)...) 

	// 创建加密模式
	ciphertext := make([]byte, len(paddedPlaintext))
	iv := make([]byte, aes.BlockSize)
	mode := cipher.NewCBCEncrypter(block, iv)

	// 执行加密操作
	mode.CryptBlocks(ciphertext, paddedPlaintext)

	fmt.Printf("%x\n", ciphertext)
}

请注意,在实际应用中,需要根据具体的需求和加密库的要求选择适当的填充方法。同时,还需要确保解密时使用相同的填充方法进行解密操作。

Go 语言 AES 加密错误 'crypto/cipher: input not full blocks' 解决方法

原文地址: https://www.cveoy.top/t/topic/pkh1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录