How to loop over Blowfish Crypto++

こ雲淡風輕ζ 提交于 2019-12-02 04:25:27

At each iteration of the loop, you have to call:

  • cipher.clear()
  • recovered.clear()

Otherwise, the StringSink's just keep adding to the end of a previous value. You will fail on the 2nd and subsequent iterations of your loop (the 1st should be OK).

Also, there is no Resynchronize, so you can't call e.Resynchronize(iv) to restart a cipher. You have to call e.SetKeyWithIV(key, key.size(), iv) at each iteration of your loop.

Below, I could not duplicate your reuse problem. The encryption object was reused, while the decryption object was created new for each iteration. The result of running the program:

$ ./cryptopp-test.exe
plain text: String 1
recovered text: String 1
plain text: String 2
recovered text: String 2
plain text: String 3
recovered text: String 3
plain text: String 4
recovered text: String 4
plain text: String 5
recovered text: String 5

AutoSeededRandomPool prng;

SecByteBlock key(Blowfish::DEFAULT_KEYLENGTH);
prng.GenerateBlock( key, key.size() );

byte iv[ Blowfish::BLOCKSIZE ];
prng.GenerateBlock( iv, sizeof(iv) );

vector<string> vv;
vv.push_back("String 1");
vv.push_back("String 2");
vv.push_back("String 3");
vv.push_back("String 4");
vv.push_back("String 5");

string plain, cipher, recovered;

try {

    EAX< Blowfish >::Encryption e1;
    e1.SetKeyWithIV( key, key.size(), iv, sizeof(iv) );

    for(unsigned i = 0; i < vv.size(); i++)
    {
        /*********************************\
        \*********************************/

        plain = vv[i];
        cout << "plain text: " << plain << endl;

        e1.SetKeyWithIV( key, key.size(), iv, sizeof(iv) );

        cipher.clear();
        StringSource ss1(plain, true,
                         new AuthenticatedEncryptionFilter( e1,
                             new StringSink( cipher )
                         )  ); // StringSource

        /*********************************\
        \*********************************/

        EAX< Blowfish >::Decryption d2;
        d2.SetKeyWithIV( key, key.size(), iv, sizeof(iv) );

        recovered.clear();
        StringSource ss2(cipher, true,
                         new AuthenticatedDecryptionFilter( d2,
                             new StringSink( recovered ),
                             AuthenticatedDecryptionFilter::THROW_EXCEPTION
                         ) ); // StringSource

        cout << "recovered text: " << recovered << endl;
    }

} catch (const Exception& ex) {
    cerr << ex.what() << endl;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!