| 43 | |
| 44 | template <typename T> |
| 45 | static int CBCEncrypt(const T& enc, const unsigned char iv[AES_BLOCKSIZE], const unsigned char* data, int size, bool pad, unsigned char* out) |
| 46 | { |
| 47 | int written = 0; |
| 48 | int padsize = size % AES_BLOCKSIZE; |
| 49 | unsigned char mixed[AES_BLOCKSIZE]; |
| 50 | |
| 51 | if (!data || !size || !out) |
| 52 | return 0; |
| 53 | |
| 54 | if (!pad && padsize != 0) |
| 55 | return 0; |
| 56 | |
| 57 | memcpy(mixed, iv, AES_BLOCKSIZE); |
| 58 | |
| 59 | // Write all but the last block |
| 60 | while (written + AES_BLOCKSIZE <= size) { |
| 61 | for (int i = 0; i != AES_BLOCKSIZE; i++) |
| 62 | mixed[i] ^= *data++; |
| 63 | enc.Encrypt(out + written, mixed); |
| 64 | memcpy(mixed, out + written, AES_BLOCKSIZE); |
| 65 | written += AES_BLOCKSIZE; |
| 66 | } |
| 67 | if (pad) { |
| 68 | // For all that remains, pad each byte with the value of the remaining |
| 69 | // space. If there is none, pad by a full block. |
| 70 | for (int i = 0; i != padsize; i++) |
| 71 | mixed[i] ^= *data++; |
| 72 | for (int i = padsize; i != AES_BLOCKSIZE; i++) |
| 73 | mixed[i] ^= AES_BLOCKSIZE - padsize; |
| 74 | enc.Encrypt(out + written, mixed); |
| 75 | written += AES_BLOCKSIZE; |
| 76 | } |
| 77 | return written; |
| 78 | } |
| 79 | |
| 80 | template <typename T> |
| 81 | static int CBCDecrypt(const T& dec, const unsigned char iv[AES_BLOCKSIZE], const unsigned char* data, int size, bool pad, unsigned char* out) |