2 * Copyright (C) 2011 Gregor Pintar <grpintar@gmail.com>
4 * Permission is granted to deal in this work without any restriction,
5 * including unlimited rights to use, publicly perform, publish,
6 * reproduce, relicence, modify, merge, and/or distribute in any form,
7 * for any purpose, with or without fee, and by any means.
9 * This work is provided "AS IS" and WITHOUT WARRANTY of any kind,
10 * to the utmost extent permitted by applicable law. In no event
11 * shall a licensor, author or contributor be held liable for any
12 * issues arising in any way out of dealing in the work.
19 #include <kripto/macros.h>
20 #include <kripto/memwipe.h>
21 #include <kripto/block.h>
22 #include <kripto/mode.h>
23 #include <kripto/mode_desc.h>
24 #include <kripto/stream.h>
25 #include <kripto/stream_desc.h>
27 #include <kripto/mode/ctr.h>
31 kripto_stream_desc
*desc
;
32 const kripto_block
*block
;
33 unsigned int block_size
;
39 static size_t ctr_crypt
50 for(i
= 0; i
< len
; i
++)
52 if(s
->used
== s
->block_size
)
54 kripto_block_encrypt(s
->block
, s
->x
, s
->buf
);
57 for(n
= s
->block_size
- 1; n
; n
--)
61 U8(out
)[i
] = CU8(in
)[i
] ^ s
->buf
[s
->used
++];
67 static size_t ctr_prng
77 for(i
= 0; i
< len
; i
++)
79 if(s
->used
== s
->block_size
)
81 kripto_block_encrypt(s
->block
, s
->x
, s
->buf
);
84 for(n
= s
->block_size
- 1; n
; n
--)
88 U8(out
)[i
] = s
->buf
[s
->used
++];
94 static void ctr_destroy(kripto_stream
*s
)
96 kripto_memwipe(s
, sizeof(kripto_stream
)
97 + (s
->block_size
<< 1)
98 + sizeof(kripto_stream_desc
)
104 static kripto_stream
*ctr_create
106 const kripto_block
*block
,
108 const unsigned int iv_len
112 kripto_block_desc
*b
;
113 struct kripto_stream_desc
*stream
;
115 b
= kripto_block_get_desc(block
);
117 s
= malloc(sizeof(kripto_stream
)
118 + (kripto_block_size(b
) << 1)
119 + sizeof(kripto_stream_desc
)
123 s
->block_size
= kripto_block_size(b
);
125 stream
= (struct kripto_stream_desc
*)
126 ((uint8_t *)s
+ sizeof(kripto_stream
));
128 s
->x
= (uint8_t *)stream
+ sizeof(kripto_stream_desc
);
129 s
->buf
= s
->x
+ s
->block_size
;
131 stream
->encrypt
= &ctr_crypt
;
132 stream
->decrypt
= &ctr_crypt
;
133 stream
->prng
= &ctr_prng
;
135 stream
->destroy
= &ctr_destroy
;
136 stream
->max_key
= kripto_block_max_key(b
);
137 stream
->max_iv
= s
->block_size
;
141 if(iv_len
) memcpy(s
->x
, iv
, iv_len
);
142 memset(s
->x
+ iv_len
, 0, s
->block_size
- iv_len
);
144 s
->used
= s
->block_size
;
150 static const struct kripto_mode_desc ctr
=
156 kripto_mode_desc
*const kripto_mode_ctr
= &ctr
;