我尝试使用 Crypto++ 实现蛇算法。 但我发现与 Cryptopp::Serpent 相关的文件很少(包括 http://www.cryptopp.com/ ) 谁能给我一个简单的 Serpent 示例?
最佳答案
来自Crypto++ wiki page on Serpent :
AutoSeededRandomPool prng;
SecByteBlock key(Serpent::DEFAULT_KEYLENGTH);
prng.GenerateBlock(key, key.size());
byte iv[Serpent::BLOCKSIZE];
prng.GenerateBlock(iv, sizeof(iv));
string plain = "CBC Mode Test";
string cipher, encoded, recovered;
/*********************************\
\*********************************/
try
{
cout << "plain text: " << plain << endl;
CBC_Mode< Serpent >::Encryption e;
e.SetKeyWithIV(key, key.size(), iv);
// The StreamTransformationFilter adds padding
// as required. ECB and CBC Mode must be padded
// to the block size of the cipher.
StringSource ss1(plain, true,
new StreamTransformationFilter(e,
new StringSink(cipher)
) // StreamTransformationFilter
); // StringSource
}
catch(const CryptoPP::Exception& e)
{
cerr << e.what() << endl;
exit(1);
}
/*********************************\
\*********************************/
// Pretty print
StringSource ss2(cipher, true,
new HexEncoder(
new StringSink(encoded)
) // HexEncoder
); // StringSource
cout << "cipher text: " << encoded << endl;
/*********************************\
\*********************************/
try
{
CBC_Mode< Serpent >::Decryption d;
d.SetKeyWithIV(key, key.size(), iv);
// The StreamTransformationFilter removes
// padding as required.
StringSource ss3(cipher, true,
new StreamTransformationFilter(d,
new StringSink(recovered)
) // StreamTransformationFilter
); // StringSource
cout << "recovered text: " << recovered << endl;
}
catch(const CryptoPP::Exception& e)
{
cerr << e.what() << endl;
exit(1);
}
典型的输出如下所示。请注意,每次运行都会产生不同的结果,因为 key 和初始化 vector 是随机生成的。
$ ./Driver.exe
key: BE4295539F6BD1752FD0A80229EF8847
iv: 00963F59224794D5AD4252094358FBC3
plain text: CBC Mode Test
cipher text: CF2CF2547E02F6D34D97246E8042ED89
recovered text: CBC Mode Test
没什么好说的。您可以换入或换出任何分组密码。相同的代码将适用于 AES、Camellia、3DES 等。
关于c++ - Crypto++ 中的蛇实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26837758/