Sunday, August 22, 2010

encrypt(3) example usage

A while back I had someone ask about how to use the encrypt() function under Linux. He had tried the man page, encrypt(3), which even contains an example usage. Unfortunately for him, the example given was terribly broken. I managed to find a post by Jens Thoms Törring which contained a working sample (though there was an off-by-one error which Mr. Törring later brought to my attention).  Since the current man page at the time had a broken example, I thought I would send a patch in to have it fixed.  That was a little over a year ago, but guess what?  Still the same broken code!  I don't know why the patch was not applied.  Perhaps it was a crappy patch (I don't normally do patches, so I might have done it wrong).  Or maybe the maintainer of the man pages was too busy.  I don't really know what happened. Since speculation is pretty much useless, I thought I might post the code here, for anyone else searching for a useful example of encrypt usage.
/* Modified from original source code
 * written by Jens Thoms Toerring.  The original
 * can be found on comp.os.linux.development.
 */

#define _XOPEN_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <crypt.h>

/* You need to link with libcrypt (-lcrypt) 
 * to compile this example with glibc.
 */

int main(void)
{
    char key[64];
    char orig[9] = "eggplant";
    char buf[64];
    char txt[9];
    int i, j;

    for (i = 0; i < 64; i++) {
        key[i] = rand() & 1;
    }

    for (i = 0; i < 8; i++) {
        for (j = 0; j < 8; j++) {
            buf[i * 8 + j] = orig[i] >> j & 1;
        }
        setkey(key);
    }
    printf("Before encrypting: %s\n", orig);

    encrypt(buf, 0);
    for (i = 0; i < 8; i++) {
        for (j = 0, txt[i] = '\0'; j < 8; j++) {
            txt[i] |= buf[i * 8 + j] << j;
        }
        txt[8] = '\0';
    }
    printf("After encrypting:  %s\n", txt);

    encrypt(buf, 1);
    for (i = 0; i < 8; i++) {
        for (j = 0, txt[i] = '\0'; j < 8; j++) {
            txt[i] |= buf[i * 8 + j] << j;
        }
        txt[8] = '\0';
    }
    printf("After decrypting:  %s\n", txt);

    return 0;
}

No comments:

Post a Comment