| 75 | |
| 76 | template <typename T> |
| 77 | static int CBCEncrypt(const T& enc, const unsigned char iv[AES_BLOCKSIZE], const unsigned char* data, int size, bool pad, unsigned char* out) |
| 78 | { |
| 79 | int written = 0; |
| 80 | int padsize = size % AES_BLOCKSIZE; |
| 81 | unsigned char mixed[AES_BLOCKSIZE]; |
| 82 | |
| 83 | if (!data || !size || !out) |
| 84 | return 0; |
| 85 | |
| 86 | if (!pad && padsize != 0) |
| 87 | return 0; |
| 88 | |
| 89 | memcpy(mixed, iv, AES_BLOCKSIZE); |
| 90 | |
| 91 | // Write all but the last block |
| 92 | while (written + AES_BLOCKSIZE <= size) { |
| 93 | for (int i = 0; i != AES_BLOCKSIZE; i++) |
| 94 | mixed[i] ^= *data++; |
| 95 | enc.Encrypt(out + written, mixed); |
| 96 | memcpy(mixed, out + written, AES_BLOCKSIZE); |
| 97 | written += AES_BLOCKSIZE; |
| 98 | } |
| 99 | if (pad) { |
| 100 | // For all that remains, pad each byte with the value of the remaining |
| 101 | // space. If there is none, pad by a full block. |
| 102 | for (int i = 0; i != padsize; i++) |
| 103 | mixed[i] ^= *data++; |
| 104 | for (int i = padsize; i != AES_BLOCKSIZE; i++) |
| 105 | mixed[i] ^= AES_BLOCKSIZE - padsize; |
| 106 | enc.Encrypt(out + written, mixed); |
| 107 | written += AES_BLOCKSIZE; |
| 108 | } |
| 109 | return written; |
| 110 | } |
| 111 | |
| 112 | template <typename T> |
| 113 | static int CBCDecrypt(const T& dec, const unsigned char iv[AES_BLOCKSIZE], const unsigned char* data, int size, bool pad, unsigned char* out) |