|
DES encryption
Encryption with the SSLeay library, compile with command
gcc crypto.c -I/usr/local/ssl/include
-L/usr/local/ssl/lib -lcrypto
Example of normal triple DES encryption which works only on an 8-byte
buffer:
/*****************************************************************************/
/*
*/
/* File: crypto.c
*/
/*
*/
/* Compile with: gcc program.c -lcrypto
(SSLeay) */
/*
*/
/*****************************************************************************/
#include <stdio.h>
#include <des.h>
#define bufsize 1024
/* Note how this truncates to 8 characters
*/
main ()
{ char
in[bufsize],out[bufsize],back[bufsize];
des_cblock key1,key2,key3,seed =
{0xFE,0xDC,0xBA,0x98,0x76,0x54,0x32,0x10};
des_key_schedule
ks1,ks2,ks3;
strcpy(in,"1 2 3 4 5 6 7 8 9 a b c d e f g h i
j k");
des_random_seed(seed);
des_random_key(key1);
des_random_key(key2);
des_random_key(key3);
des_set_key((C_Block
*)key1,ks1);
des_set_key((C_Block
*)key2,ks2);
des_set_key((C_Block
*)key3,ks3);
des_ecb3_encrypt((C_Block *)in,(C_Block
*)out,ks1,ks2,ks3,DES_ENCRYPT);
printf("Encrypted [%s] into
[%s]\n",in,out);
des_ecb3_encrypt((C_Block *)out,(C_Block
*)back,ks1,ks2,ks3,DES_DECRYPT);
printf("and back to.. [%s]\n",back);
}
Triple DES, chaining mode, for longer strings (which must be a multiple of
8 bytes):
/*****************************************************************************/
/*
*/
/* File: crypto.c
*/
/*
*/
/* Compile with: gcc program.c -lcrypto
(SSLeay) */
/*
*/
/*****************************************************************************/
#include <stdio.h>
#include <des.h>
#define bufsize 1024
/* This can be used on arbitrary length
buffers */
main ()
{ char
in[bufsize],out[bufsize],back[bufsize],workvec[bufsize];
des_cblock key1,key2,key3,seed =
{0xFE,0xDC,0xBA,0x98,0x76,0x54,0x32,0x10};
des_key_schedule
ks1,ks2,ks3;
strcpy(in,"1 2 3 4 5 6 7 8 9 a b c d e f g h i
j k l m n o p q r s t u v w x y z");
des_random_seed(seed);
des_random_key(key1);
des_random_key(key2);
des_random_key(key3);
des_set_key((C_Block
*)key1,ks1);
des_set_key((C_Block
*)key2,ks2);
des_set_key((C_Block
*)key3,ks3);
/* This work vector can be intialized t
anything ...*/
memset(workvec,0,bufsize);
des_ede3_cbc_encrypt((C_Block *)in,(C_Block
*)out,(long)strlen(in),
ks1,ks2,ks3,(C_Block
*)workvec,DES_ENCRYPT);
printf("Encypted [%s] into
[something]\n",in);
/* .. but this must be initialized the same as
above */
memset(workvec,0,bufsize);
/* Note that the length is the original
length, not strlen(out) */
des_ede3_cbc_encrypt((C_Block *)out,(C_Block
*)back,(long)strlen(in),
ks1,ks2,ks3,(C_Block
*)workvec,DES_DECRYPT);
printf("and back to.. [%s]\n",back);
}
|