The Encryption routine
| Under Live JounalThe encryption routine takes two parameters – the file descriptors of input file and the output file to which the encrypted data is to be saved. It is always a good idea to zero-fill your buffers using the memset or bzero commands before using the buffers with data. This is especially important if you plan to reuse the buffers. In the program below, the input data is being encrypted in blocks of 1K each.
The steps for encryption are as follows :-
- Create a cipher context
- Initialize the cipher context with the values of Key and IV
- Call EVP_EncryptUpdate to encrypt successive blocks of 1k eack
- Call EVP_EncryptFinal to encrypt “leftover” data
- Finally call EVP_CIPHER_CTX_cleanup to discard all the sensitive information from memory
You may be wondering what “leftover” data is? As mentioned earlier, Blowfish encrypts information in blocks of 64-bit each. Sometimes we may not have 64 bits to make up a block. This may happen if the buffer size in the program below or the file/input data size is not a integral multiple of 8 bytes(64-bits).So accordingly the data is padded and then the partial block is encrypted using EVP_EncryptFinal. The length of the encoded data block is stored in the variable tlen and added to the final length.
int
encrypt (int infd, int outfd)
{
unsigned char outbuf[OP_SIZE];
int olen, tlen, n;
char inbuff[IP_SIZE];
EVP_CIPHER_CTX ctx;
EVP_CIPHER_CTX_init (& ctx);
EVP_EncryptInit (& ctx, EVP_bf_cbc (), key, iv);
for (;;)
{
bzero (& inbuff, IP_SIZE);
if ((n = read (infd, inbuff, IP_SIZE)) == -1)
{
perror ("read error");
break;
}
else if (n == 0)
break;
if (EVP_EncryptUpdate (& ctx, outbuf, & olen, inbuff, n) != 1)
{
printf ("error in encrypt update\n");
return 0;
}
if (EVP_EncryptFinal (& ctx, outbuf + olen, & tlen) != 1)
{
printf ("error in encrypt final\n");
return 0;
}
olen += tlen;
if ((n = write (outfd, outbuf, olen)) == -1)
perror ("write error");
}
EVP_CIPHER_CTX_cleanup (& ctx);
return 1;
}