1 /*
2 * Copyright (c) 2000, 2001, 2002 X-Way Rights BV
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 *
18 */
19
20 /*!\file blockpad.c
21 * \brief Blockcipher padding algorithms.
22 * \author Bob Deblier <bob.deblier@telenet.be>
23 * \ingroup BC_m
24 */
25
26 #define BEECRYPT_DLL_EXPORT
27
28 #if HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include "beecrypt/blockpad.h"
33
pkcs5Pad(size_t blockbytes,memchunk * tmp)34 memchunk* pkcs5Pad(size_t blockbytes, memchunk* tmp)
35 {
36 if (tmp)
37 {
38 byte padvalue = blockbytes - (tmp->size % blockbytes);
39
40 tmp = memchunkResize(tmp, tmp->size + padvalue);
41
42 if (tmp)
43 memset(tmp->data - padvalue, padvalue, padvalue);
44 }
45
46 return tmp;
47 }
48
pkcs5Unpad(size_t blockbytes,memchunk * tmp)49 memchunk* pkcs5Unpad(size_t blockbytes, memchunk* tmp)
50 {
51 if (tmp)
52 {
53 byte padvalue = tmp->data[tmp->size - 1];
54
55 unsigned int i;
56
57 if (padvalue > blockbytes)
58 return (memchunk*) 0;
59
60 for (i = (tmp->size - padvalue); i < (tmp->size - 1); i++)
61 {
62 if (tmp->data[i] != padvalue)
63 return (memchunk*) 0;
64 }
65
66 tmp->size -= padvalue;
67 /* tmp->data = (byte*) realloc(tmp->data, tmp->size); */
68 }
69
70 return tmp;
71 }
72
pkcs5PadCopy(size_t blockbytes,const memchunk * src)73 memchunk* pkcs5PadCopy(size_t blockbytes, const memchunk* src)
74 {
75 memchunk* tmp;
76 byte padvalue = blockbytes - (src->size % blockbytes);
77
78 if (src == (memchunk*) 0)
79 return (memchunk*) 0;
80
81 tmp = memchunkAlloc(src->size + padvalue);
82
83 if (tmp)
84 {
85 memcpy(tmp->data, src->data, src->size);
86 memset(tmp->data+src->size, padvalue, padvalue);
87 }
88
89 return tmp;
90 }
91
pkcs5UnpadCopy(size_t blockbytes,const memchunk * src)92 memchunk* pkcs5UnpadCopy(size_t blockbytes, const memchunk* src)
93 {
94 memchunk* tmp;
95 byte padvalue;
96 unsigned int i;
97
98 if (src == (memchunk*) 0)
99 return (memchunk*) 0;
100
101 padvalue = src->data[src->size - 1];
102
103 for (i = (src->size - padvalue); i < (src->size - 1); i++)
104 {
105 if (src->data[i] != padvalue)
106 return (memchunk*) 0;
107 }
108
109 tmp = memchunkAlloc(src->size - padvalue);
110
111 if (tmp)
112 memcpy(tmp->data, src->data, tmp->size);
113
114 return tmp;
115 }
116