3 * Cipher block chaining mode, with cipher text stealing.
6 /* nettle, low-level cryptographics library
8 * Copyright (C) 2003 Simon Josefsson
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., 59 Temple Place - Suite 330, Boston,
39 cbc_cts_encrypt (void *ctx
,
44 unsigned block_size
, uint8_t * iv
,
45 unsigned length
, uint8_t * dst
, const uint8_t * src
)
47 unsigned nblocks
= length
/ block_size
;
48 unsigned restbytes
= (length
% block_size
) == 0 ?
49 block_size
: length
% block_size
;
51 for (; nblocks
; nblocks
--, src
+= block_size
, dst
+= block_size
)
53 memxor (iv
, src
, block_size
);
54 f (ctx
, block_size
, dst
, iv
);
55 memcpy (iv
, dst
, block_size
);
58 if (length
> block_size
)
60 memcpy (dst
, dst
- block_size
, restbytes
);
62 memcpy (dst
, src
, restbytes
);
63 memset (dst
+ restbytes
, 0, block_size
- restbytes
);
64 memxor (iv
, dst
, block_size
);
65 f (ctx
, block_size
, dst
, iv
);
70 cbc_cts_decrypt (void *ctx
,
75 unsigned block_size
, uint8_t * iv
,
76 unsigned length
, uint8_t * dst
, const uint8_t * src
)
78 unsigned nblocks
= length
/ block_size
;
79 unsigned restbytes
= (length
% block_size
) == 0 ?
80 block_size
: length
% block_size
;
81 uint8_t *tmpiv
= alloca (block_size
);
83 if (length
> block_size
)
86 if ((length
% block_size
) == 0)
90 for (; nblocks
; nblocks
--, src
+= block_size
, dst
+= block_size
)
92 memcpy (tmpiv
, src
, block_size
);
93 f (ctx
, block_size
, dst
, src
);
94 memxor (dst
, iv
, block_size
);
95 memcpy (iv
, tmpiv
, block_size
);
98 if (length
> block_size
)
100 memcpy (iv
, src
+ block_size
, restbytes
);
101 f (ctx
, block_size
, dst
, src
);
102 memxor (dst
, iv
, restbytes
);
103 memcpy (dst
+ block_size
, dst
, restbytes
);
104 memcpy (iv
+ restbytes
, dst
+ restbytes
, block_size
- restbytes
);
105 f (ctx
, block_size
, dst
, iv
);
106 memxor (dst
, tmpiv
, block_size
);