Reformat and "modernise" the sign.c demo.
[openssl.git] / demos / maurice / example3.c
1 /* NOCW */
2 /*
3         Please read the README file for condition of use, before
4         using this software.
5
6         Maurice Gittens  <mgittens@gits.nl>   January 1997
7
8 */
9
10 #include <stdio.h>
11 #include <unistd.h>
12 #include <fcntl.h>
13 #include <sys/stat.h>
14 #include <openssl/evp.h>
15
16 #define STDIN           0
17 #define STDOUT          1
18 #define BUFLEN          512 
19 #define INIT_VECTOR     "12345678"
20 #define ENCRYPT         1
21 #define DECRYPT         0
22 #define ALG             EVP_des_ede3_cbc()
23
24 static const char *usage = "Usage: example3 [-d] password\n";
25
26 void do_cipher(char *,int);
27
28 int main(int argc, char *argv[])
29 {
30         if ((argc == 2))        
31         {
32                 do_cipher(argv[1],ENCRYPT);
33         }       
34         else if ((argc == 3) && !strcmp(argv[1],"-d"))
35         {
36                 do_cipher(argv[2],DECRYPT);
37         }
38         else
39         {
40                 fprintf(stderr,"%s", usage);
41                 exit(1);
42         }
43
44         return 0;               
45 }
46
47 void do_cipher(char *pw, int operation)
48 {
49         char buf[BUFLEN];
50         char ebuf[BUFLEN + 8];
51         unsigned int ebuflen; /* rc; */
52         unsigned char iv[EVP_MAX_IV_LENGTH], key[EVP_MAX_KEY_LENGTH];
53         /* unsigned int ekeylen, net_ekeylen;  */
54         EVP_CIPHER_CTX ectx;
55         
56         memcpy(iv, INIT_VECTOR, sizeof(iv));
57
58         EVP_BytesToKey(ALG, EVP_md5(), "salu", pw, strlen(pw), 1, key, iv);
59
60         EVP_CipherInit(&ectx, ALG, key, iv, operation);
61
62         while(1)
63         {
64                 int readlen = read(STDIN, buf, sizeof(buf));
65         
66                 if (readlen <= 0)
67                 {
68                         if (!readlen)
69                            break;
70                         else
71                         {
72                                 perror("read");
73                                 exit(1);
74                         }
75                 }
76
77                 EVP_CipherUpdate(&ectx, ebuf, &ebuflen, buf, readlen);
78
79                 write(STDOUT, ebuf, ebuflen);
80         }
81
82         EVP_CipherFinal(&ectx, ebuf, &ebuflen); 
83
84         write(STDOUT, ebuf, ebuflen); 
85 }