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