|
The simple example illustrates how to authenticate, compress and encipher
a string, and how to decipher, decompress and verify the MAC
#include <LEDA/coding/crypt.h> //
contains all cryptography classes
using namespace leda;
void generate_keys(CryptKey& auth_key, CryptKey& cipher_key)
{
// key generation (two keys)
CryptByteString passphrase = CryptKey::read_passphrase("Passphrase: ");
CryptByteString salt(1);
salt[0] = 'a'; // for authentication
auth_key = CryptKey::generate_key(128/8, passphrase, salt);
salt[0] = 'c'; // for enciphering/deciphering
cipher_key = CryptKey::generate_key(128/8, passphrase, salt);
}
int main()
{
string str = "Hello World";
CryptKey auth_key, cipher_key;
// encode: MAC -> compress -> encipher
typedef CoderPipe3< OMACCoder<>, PPMIICoder, CBCCoder<> > CryptCoder;
encoding_ofstream<CryptCoder> out("foo");
generate_keys(auth_key, cipher_key);
out.get_coder()->get_coder1()->set_key(auth_key);
out.get_coder()->get_coder3()->set_key(cipher_key);
out << str << "\n";
out.close();
if (out.fail()) std::cout << "error writing foo" << "\n";
// decode: decipher -> decompress -> MAC
decoding_ifstream<CryptCoder> in("foo");
generate_keys(auth_key, cipher_key);
in.get_coder()->get_coder1()->set_key(auth_key);
in.get_coder()->get_coder3()->set_key(cipher_key);
str.read_line(in);
in.finish(); // read till EOF is reached and then close "in"
if (in.fail()) std::cout << "error authenticating foo" << "\n";
std::cout << "decoded string: " << str << "\n";
return 0;
}
|