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 CBC |
|
14 |
|
15 int cbc_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_CBC *cbc) |
|
16 { |
|
17 int x, err; |
|
18 unsigned char tmp[MAXBLOCKSIZE], tmp2[MAXBLOCKSIZE]; |
|
19 |
|
20 _ARGCHK(pt != NULL); |
|
21 _ARGCHK(ct != NULL); |
|
22 _ARGCHK(cbc != NULL); |
|
23 |
|
24 /* decrypt the block from ct into tmp */ |
|
25 if ((err = cipher_is_valid(cbc->cipher)) != CRYPT_OK) { |
|
26 return err; |
|
27 } |
15
|
28 _ARGCHK(cipher_descriptor[cbc->cipher].ecb_decrypt != NULL); |
|
29 |
3
|
30 /* is blocklen valid? */ |
|
31 if (cbc->blocklen < 0 || cbc->blocklen > (int)sizeof(cbc->IV)) { |
|
32 return CRYPT_INVALID_ARG; |
|
33 } |
|
34 |
15
|
35 /* decrypt and xor IV against the plaintext of the previous step */ |
|
36 cipher_descriptor[cbc->cipher].ecb_decrypt(ct, tmp, &cbc->key); |
3
|
37 for (x = 0; x < cbc->blocklen; x++) { |
|
38 /* copy CT in case ct == pt */ |
|
39 tmp2[x] = ct[x]; |
|
40 |
|
41 /* actually decrypt the byte */ |
|
42 pt[x] = tmp[x] ^ cbc->IV[x]; |
|
43 } |
|
44 |
|
45 /* replace IV with this current ciphertext */ |
|
46 for (x = 0; x < cbc->blocklen; x++) { |
|
47 cbc->IV[x] = tmp2[x]; |
|
48 } |
|
49 #ifdef CLEAN_STACK |
|
50 zeromem(tmp, sizeof(tmp)); |
|
51 zeromem(tmp2, sizeof(tmp2)); |
|
52 #endif |
|
53 return CRYPT_OK; |
|
54 } |
|
55 |
|
56 #endif |
|
57 |