API¶
This page presents several coding examples that demonstrate the interface of the library.
Decryption¶
We are going to decrypt a file encrypted with gpg as below:
wget -O war_and_peace.html https://en.wikipedia.org/wiki/War_and_Peace echo -n "swordfish" | gpg2 --batch -c --cipher-algo AES256 --passphrase-fd 0 -o war_and_peace.html.gpg war_and_peace.html
The encrypted file was 58 KB when I ran the command. Next we will decrypt the file with LibEncryptMsg.
#include <iostream>
#include <fstream>
#include <string>
#include "encryptmsg/message_decryption.h"
char *AsChar(uint8_t *data)
{
return reinterpret_cast<char*>(data);
}
int main(int argc, char **argv)
{
if(argc < 2)
return -1;
// Open file for reading
std::string file_name = argv[1];
std::ifstream in(argv[1], std::ios_base::binary);
// Initialise the decryption
std::string pwd = "swordfish";
EncryptMsg::MessageReader reader;
// Convert the password string to a vector of bytes and use it as the
// secret:
reader.Start(EncryptMsg::SafeVector(pwd.begin(), pwd.end()));
EncryptMsg::SafeVector buffer;
buffer.resize(64);
// Process bytes one buffer at a time
std::fstream::off_type read;
while( (read = in.readsome(AsChar(buffer.data()), buffer.size())) > 0)
{
buffer.resize(read);
// buffer provides input and receives output
reader.Update(buffer);
std::cout.write(AsChar(buffer.data()), buffer.size());
buffer.resize(64);
}
buffer.clear();
// Finish works as Update but it also notifies MessageReader that the
// stream is finished
reader.Finish(buffer);
std::cout.write(AsChar(buffer.data()), buffer.size());
return 0;
}