3
|
1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis |
|
2 * |
|
3 * LibTomCrypt is a library that provides various cryptographic |
|
4 * algorithms in a highly modular and flexible manner. |
|
5 * |
|
6 * The library is free for all purposes without any express |
|
7 * guarantee it works. |
|
8 * |
|
9 * Tom St Denis, [email protected], http://libtomcrypt.org |
|
10 */ |
|
11 #include "mycrypt.h" |
|
12 |
|
13 #ifdef CTR |
|
14 |
|
15 int ctr_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, symmetric_CTR *ctr) |
|
16 { |
|
17 int x, err; |
|
18 |
|
19 _ARGCHK(pt != NULL); |
|
20 _ARGCHK(ct != NULL); |
|
21 _ARGCHK(ctr != NULL); |
|
22 |
|
23 if ((err = cipher_is_valid(ctr->cipher)) != CRYPT_OK) { |
|
24 return err; |
|
25 } |
|
26 |
|
27 /* is blocklen/padlen valid? */ |
|
28 if (ctr->blocklen < 0 || ctr->blocklen > (int)sizeof(ctr->ctr) || |
|
29 ctr->padlen < 0 || ctr->padlen > (int)sizeof(ctr->pad)) { |
|
30 return CRYPT_INVALID_ARG; |
|
31 } |
|
32 |
|
33 while (len-- > 0) { |
|
34 /* is the pad empty? */ |
|
35 if (ctr->padlen == ctr->blocklen) { |
|
36 /* increment counter */ |
|
37 if (ctr->mode == 0) { |
|
38 /* little-endian */ |
|
39 for (x = 0; x < ctr->blocklen; x++) { |
|
40 ctr->ctr[x] = (ctr->ctr[x] + (unsigned char)1) & (unsigned char)255; |
|
41 if (ctr->ctr[x] != (unsigned char)0) { |
|
42 break; |
|
43 } |
|
44 } |
|
45 } else { |
|
46 /* big-endian */ |
|
47 for (x = ctr->blocklen-1; x >= 0; x--) { |
|
48 ctr->ctr[x] = (ctr->ctr[x] + (unsigned char)1) & (unsigned char)255; |
|
49 if (ctr->ctr[x] != (unsigned char)0) { |
|
50 break; |
|
51 } |
|
52 } |
|
53 } |
|
54 |
|
55 /* encrypt it */ |
|
56 cipher_descriptor[ctr->cipher].ecb_encrypt(ctr->ctr, ctr->pad, &ctr->key); |
|
57 ctr->padlen = 0; |
|
58 } |
|
59 *ct++ = *pt++ ^ ctr->pad[ctr->padlen++]; |
|
60 } |
|
61 return CRYPT_OK; |
|
62 } |
|
63 |
|
64 #endif |