#include #include #include void hdata(char *msg, char s[], int len) { int i; printf("%s", msg); for (i = 0; i < len; i++) { printf("%02x", (unsigned char) s[i]); if ((i % 4) == 3 && i != (len-1)) putchar(' '); } putchar('\n'); } int main(int argc, char *argv[]) { char key[8] = /* 8 bytes; must set parity */ {0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80}; char iv[8]; /* Initialize to random data */ char saveiv[8]; char data[]= /* 23 data bytes plus a null */ "Here's some input data!"; int i, rc; /* Make sure I didn't miscount -- you have to handle the problem */ /* assert((sizeof data % 8) == 0); */ /* Set the parity on the key */ des_setparity(key); printf("Data: %s\n", data); hdata(" ", data, sizeof data); /* Pick a random IV. For simplicity's sake, I'm not setting the seed */ for (i = 0; i < sizeof iv; i++) iv[i] = random() >> 24; hdata("IV: ", iv, sizeof iv); /* Save the IV */ memcpy(saveiv, iv, sizeof saveiv); rc = cbc_crypt(key, data, sizeof data, DES_ENCRYPT, iv); switch (rc) { case DESERR_NONE: break; case DESERR_NOHWDEVICE: /* Shouldn't get this, but I do... */ printf("Hardware requested, not found\n"); break; case DESERR_HWERROR: /* Man page gives the wrong name... */ printf("Hardware error\n"); break; case DESERR_BADPARAM: printf("Parameter error\n"); break; } hdata("ciphertext: ", data, sizeof data); hdata("new IV: ", iv, sizeof iv); putchar('\n'); rc = cbc_crypt(key, data, sizeof data, DES_DECRYPT, saveiv); switch (rc) { case DESERR_NONE: break; case DESERR_NOHWDEVICE: /* Shouldn't get this, but I do... */ printf("Hardware requested, not found\n"); break; case DESERR_HWERROR: printf("Hardware error\n"); break; case DESERR_BADPARAM: printf("Parameter error\n"); break; } hdata("plaintext: ", data, sizeof data); printf("Decrypted: %s\n", data); return 0; }