chiark / gitweb /
Socket address stuff. Sockid is broken still.
[chiark-tcl.git] / crypto / bcmode.c
1 /*
2  */
3   
4 #include "hbytes.h"
5
6 static const char *mode_cbc_encrypt(Byte *data, int blocks,
7                                     const Byte *iv, Byte *chain,
8                                     const BlockCipherAlgInfo *alg, int encr,
9                                     int blocksize, const void *sch) {
10   memcpy(chain,iv,blocksize);
11   alg->byteswap(chain);
12   
13   while (blocks > 0) {
14     alg->byteswap(data);
15
16     memxor(data, chain, blocksize);
17     alg->encrypt.crypt(sch, data, data);
18     memcpy(chain, data, blocksize);
19
20     alg->byteswap(data);
21     blocks--; data += blocksize;
22   }
23   return 0;
24 }
25
26 static const char *mode_cbc_decrypt(Byte *data, int blocks,
27                                     const Byte *iv, Byte *chain,
28                                     const BlockCipherAlgInfo *alg, int encr,
29                                     int blocksize, const void *sch) {
30   int cchain= 0;
31
32   memcpy(chain,iv,blocksize);
33   alg->byteswap(chain);
34   
35   while (blocks > 0) {
36     alg->byteswap(data);
37     
38     memcpy(chain + (cchain^blocksize), data, blocksize);
39     alg->decrypt.crypt(sch, data, data);
40     memxor(data, chain + cchain, blocksize);
41     cchain ^= blocksize;
42
43     alg->byteswap(data);
44     blocks--; data += blocksize;
45   }
46   return 0;
47 }
48
49 static const char *mode_ecb(Byte *data, int blocks,
50                             const Byte *iv, Byte *chain,
51                             const BlockCipherAlgInfo *alg, int encr,
52                             int blocksize, const void *sch) {
53   while (blocks > 0) {
54     alg->byteswap(data);
55     (encr ? &alg->encrypt : &alg->decrypt)->crypt(sch, data, data);
56     alg->byteswap(data);
57     blocks--; data += blocksize;
58   }
59   return 0;
60 }
61
62 const BlockCipherModeInfo blockciphermodeinfos[]= {
63   { "cbc", 1, 2, mode_cbc_encrypt, mode_cbc_decrypt },
64   { "ecb", 0, 0, mode_ecb,         mode_ecb         },
65   { 0 }
66 };