c++ - Crypto++ 中的蛇实现

标签 c++ cryptography crypto++

我尝试使用 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/

相关文章:

C++ 编译错误(有符号和无符号整数表达式的比较)

c++ - 我的代码在解压缩时产生垃圾

flutter - 用 Java 加密,用 dart flutter 解密

c++ - Crypto++ pbkdf2::DeriveKey() 罕见崩溃

c++ - 在 Visual Studio 2013 下为/MD 版本重建 Crypto++ 5.6.2

c++ - const 指针成员和 operator=

c++ - 无需键入整个容器定义即可引用迭代器的类型名称的有效方法?

php - 从客户端到服务器的安全文件传输

cryptography - 椭圆曲线上的点数

c++ - 如何使用 Crypto++ 库创建 HMAC 256?