在使用Crypto++库进行加密操作时,初始化向量(IV)是一个重要的概念。IV用于在加密过程中引入随机性,以防止相同的明文块产生相同的密文块。在使用某些加密模式(如CBC模式)时,IV必须被正确地生成并传递给解密函数。
你遇到的错误“StreamTransformationFilter:找到无效的PKCS #7块填充”通常是由于以下几个原因之一:
以下是一个使用Crypto++库进行AES-CBC加密和解密的示例代码:
#include <iostream>
#include <sstream>
#include <iomanip>
#include <cryptopp/aes.h>
#include <cryptopp/modes.h>
#include <cryptopp/filters.h>
#include <cryptopp/hex.h>
std::string Encrypt(const std::string& plainText, const CryptoPP::byte* key, const CryptoPP::byte* iv) {
std::string cipherText;
CryptoPP::ECB_Mode<CryptoPP::AES>::Encryption e;
e.SetKey(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::StringSource ss1(plainText, true,
new CryptoPP::StreamTransformationFilter(e,
new CryptoPP::HexEncoder(
new CryptoPP::StringSink(cipherText)
)
)
);
return cipherText;
}
std::string Decrypt(const std::string& cipherText, const CryptoPP::byte* key, const CryptoPP::byte* iv) {
std::string decryptedText;
CryptoPP::ECB_Mode<CryptoPP::AES>::Decryption d;
d.SetKey(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::StringSource ss2(cipherText, true,
new CryptoPP::HexDecoder(
new CryptoPP::StreamTransformationFilter(d,
new CryptoPP::StringSink(decryptedText)
)
)
);
return decryptedText;
}
int main() {
const std::string plainText = "Hello, World!";
const CryptoPP::byte key[CryptoPP::AES::DEFAULT_KEYLENGTH] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F };
const CryptoPP::byte iv[CryptoPP::AES::BLOCKSIZE] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F };
std::string encryptedText = Encrypt(plainText, key, iv);
std::cout << "Encrypted Text: " << encryptedText << std::endl;
std::string decryptedText = Decrypt(encryptedText, key, iv);
std::cout << "Decrypted Text: " << decryptedText << std::endl;
return 0;
}
通过确保IV的正确性和完整性,你应该能够解决“StreamTransformationFilter:找到无效的PKCS #7块填充”错误。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云