简体   繁体   中英

Serpent Implementation in Crypto++

I try to implement Serpent Algorithm using Crypto++. But I found little document related to Cryptopp::Serpent (including the http://www.cryptopp.com/ ) Can someone give me a well worked simple example of Serpent?

From the 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);
}

A typical output is shown below. Note that each run will produce different results because the key and initialization vector are randomly generated.

$ ./Driver.exe
key: BE4295539F6BD1752FD0A80229EF8847
iv: 00963F59224794D5AD4252094358FBC3
plain text: CBC Mode Test
cipher text: CF2CF2547E02F6D34D97246E8042ED89
recovered text: CBC Mode Test

There's not much to it. You can swap any block cipher in or out. The same code will work with AES, Camellia, 3DES, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM