6 /* nettle, low-level cryptographics library
8 * Copyright (C) 2005 Niels Möller
10 * The nettle library is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU Lesser General Public License as published by
12 * the Free Software Foundation; either version 2.1 of the License, or (at your
13 * option) any later version.
15 * The nettle library is distributed in the hope that it will be useful, but
16 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
17 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
18 * License for more details.
20 * You should have received a copy of the GNU Lesser General Public License
21 * along with the nettle library; see the file COPYING.LIB. If not, write to
22 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
38 #include "nettle-internal.h"
43 ctr_crypt(void *ctx
, nettle_crypt_func
*f
,
44 unsigned block_size
, uint8_t *ctr
,
45 unsigned length
, uint8_t *dst
,
50 if (length
== block_size
)
52 f(ctx
, block_size
, dst
, ctr
);
53 INCREMENT(block_size
, ctr
);
54 memxor(dst
, src
, block_size
);
61 for (p
= dst
, left
= length
;
63 left
-= block_size
, p
+= block_size
)
65 memcpy (p
, ctr
, block_size
);
66 INCREMENT(block_size
, ctr
);
69 f(ctx
, length
- left
, dst
, dst
);
70 memxor(dst
, src
, length
- left
);
74 TMP_DECL(buffer
, uint8_t, NETTLE_MAX_CIPHER_BLOCK_SIZE
);
75 TMP_ALLOC(buffer
, block_size
);
77 f(ctx
, block_size
, buffer
, ctr
);
78 INCREMENT(block_size
, ctr
);
79 memxor3(dst
+ length
- left
, src
+ length
- left
, buffer
, left
);
85 if (length
> block_size
)
87 TMP_DECL(buffer
, uint8_t, NBLOCKS
* NETTLE_MAX_CIPHER_BLOCK_SIZE
);
88 unsigned chunk
= NBLOCKS
* block_size
;
90 TMP_ALLOC(buffer
, chunk
);
92 for (; length
>= chunk
;
93 length
-= chunk
, src
+= chunk
, dst
+= chunk
)
97 for (n
= 0, p
= buffer
; n
< NBLOCKS
; n
++, p
+= block_size
)
99 memcpy (p
, ctr
, block_size
);
100 INCREMENT(block_size
, ctr
);
102 f(ctx
, chunk
, buffer
, buffer
);
103 memxor(dst
, buffer
, chunk
);
108 /* Final, possibly partial, blocks */
109 for (chunk
= 0; chunk
< length
; chunk
+= block_size
)
111 memcpy (buffer
+ chunk
, ctr
, block_size
);
112 INCREMENT(block_size
, ctr
);
114 f(ctx
, chunk
, buffer
, buffer
);
115 memxor3(dst
, src
, buffer
, length
);
120 TMP_DECL(buffer
, uint8_t, NETTLE_MAX_CIPHER_BLOCK_SIZE
);
121 TMP_ALLOC(buffer
, block_size
);
123 f(ctx
, block_size
, buffer
, ctr
);
124 INCREMENT(block_size
, ctr
);
125 memxor3(dst
, src
, buffer
, length
);