Alexandre Lision | 7fd5d3d | 2013-12-04 13:06:40 -0500 | [diff] [blame] | 1 | #include <stdint.h> |
| 2 | #include <stdlib.h> |
| 3 | |
| 4 | #include "twofish.h" |
| 5 | |
| 6 | void Twofish_cfb128_encrypt(Twofish_key* keyCtx, Twofish_Byte* in, |
| 7 | Twofish_Byte* out, size_t len, |
| 8 | Twofish_Byte* ivec, int32_t *num) |
| 9 | { |
| 10 | uint32_t n; |
| 11 | |
| 12 | n = *num; |
| 13 | |
| 14 | do { |
| 15 | while (n && len) { |
| 16 | *(out++) = ivec[n] ^= *(in++); |
| 17 | --len; |
| 18 | n = (n+1) % 16; |
| 19 | } |
| 20 | while (len>=16) { |
| 21 | Twofish_encrypt(keyCtx, ivec, ivec); |
| 22 | for (n=0; n<16; n+=sizeof(size_t)) { |
Alexandre Lision | ddd731e | 2014-01-31 11:50:08 -0500 | [diff] [blame] | 23 | *(size_t*)(out+n) = |
| 24 | *(size_t*)(ivec+n) ^= *(size_t*)(in+n); |
Alexandre Lision | 7fd5d3d | 2013-12-04 13:06:40 -0500 | [diff] [blame] | 25 | } |
| 26 | len -= 16; |
| 27 | out += 16; |
| 28 | in += 16; |
| 29 | } |
| 30 | n = 0; |
| 31 | if (len) { |
| 32 | Twofish_encrypt(keyCtx, ivec, ivec); |
| 33 | while (len--) { |
Alexandre Lision | ddd731e | 2014-01-31 11:50:08 -0500 | [diff] [blame] | 34 | out[n] = ivec[n] ^= in[n]; |
| 35 | ++n; |
Alexandre Lision | 7fd5d3d | 2013-12-04 13:06:40 -0500 | [diff] [blame] | 36 | } |
| 37 | } |
| 38 | *num = n; |
| 39 | return; |
| 40 | } while (0); |
| 41 | } |
| 42 | |
| 43 | |
| 44 | void Twofish_cfb128_decrypt(Twofish_key* keyCtx, Twofish_Byte* in, |
| 45 | Twofish_Byte* out, size_t len, |
| 46 | Twofish_Byte* ivec, int32_t *num) |
| 47 | { |
| 48 | uint32_t n; |
| 49 | |
| 50 | n = *num; |
| 51 | |
| 52 | do { |
| 53 | while (n && len) { |
| 54 | unsigned char c; |
| 55 | *(out++) = ivec[n] ^ (c = *(in++)); ivec[n] = c; |
| 56 | --len; |
| 57 | n = (n+1) % 16; |
| 58 | } |
| 59 | while (len>=16) { |
| 60 | Twofish_encrypt(keyCtx, ivec, ivec); |
| 61 | for (n=0; n<16; n+=sizeof(size_t)) { |
| 62 | size_t t = *(size_t*)(in+n); |
| 63 | *(size_t*)(out+n) = *(size_t*)(ivec+n) ^ t; |
| 64 | *(size_t*)(ivec+n) = t; |
| 65 | } |
| 66 | len -= 16; |
| 67 | out += 16; |
| 68 | in += 16; |
| 69 | } |
| 70 | n = 0; |
| 71 | if (len) { |
| 72 | Twofish_encrypt(keyCtx, ivec, ivec); |
| 73 | while (len--) { |
| 74 | unsigned char c; |
| 75 | out[n] = ivec[n] ^ (c = in[n]); ivec[n] = c; |
| 76 | ++n; |
| 77 | } |
| 78 | } |
| 79 | *num = n; |
| 80 | return; |
| 81 | } while (0); |
| 82 | } |