0 / 0 / 1
Регистрация: 27.03.2008
Сообщений: 75
1

Помогите разобраться с реализацией DES

27.03.2008, 18:21. Показов 6086. Ответов 18
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Есть код на СИ:
Алгоритм ясен, но на Си никогда не писала, не могли бы вы мне помочь со смыслом процедур, прокоментировать хоть как-нибудь эту прогу....Буду очень признательна!
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
#define EN0   0      /* MODE == encrypt */
#define DE1   1      /* MODE == decrypt */
 
#include <iostream.h>
#include <сstring.h>
 
typedef struct {
  unsigned long ek[32];
 unsigned long dk[32];
} des_ctx;
 
extern void deskey(unsigned char *, short);
extern void usekey(unsigned long *);
extern void cpkey(unsigned long *);
extern void des(unsigned char *, unsigned char *);
static void scrunch(unsigned char *, unsigned long *);
static void unscrun(unsigned long *, unsigned char *);
static void desfunc(unsigned long *, unsigned long *);
static void cookey(unsigned long *);
 
static unsigned long KnL[32] = { 0L };
static unsigned long KnR[32] = { 0L };
static unsigned long Kn3[32] = { 0L };
static unsigned char Df_Key[24] = {
       0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef,
       0xfe,0xdc,0xba,0x98,0x76,0x54,0x32,0x10,
       0x89,0xab,0xcd,0xef,0x01,0x23,0x45,0x67 };
 
static unsigned short bytebit[8]    = {
       0200, 0100, 040, 020, 010, 04, 02, 01 };
 
static unsigned long bigbyte[24] = {
       0x800000L,    0x400000L,     0x200000L,    0x100000L,
       0x80000L,     0x40000L,      0x20000L,     0x10000L,
       0x8000L,      0x4000L,       0x2000L,      0x1000L,
       0x800L,              0x400L,               0x200L,              0x100L,
       0x80L,               0x40L,                0x20L,               0x10L,
       0x8L,         0x4L,          0x2L,         0x1L   };
 
 
static unsigned char pc1[56] = {
       56, 48, 40, 32, 24, 16,  8,   0, 57, 49, 41, 33, 25, 17,
        9,  1, 58, 50, 42, 34, 26,  18, 10,  2, 59, 51, 43, 35,
       62, 54, 46, 38, 30, 22, 14,   6, 61, 53, 45, 37, 29, 21,
       13,  5, 60, 52, 44, 36, 28,  20, 12,  4, 27, 19, 11,  3 };
 
static unsigned char totrot[16] = {
       1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28 };
 
static unsigned char pc2[48] = {
       13, 16, 10, 23,  0,  4,       2, 27, 14,  5, 20,  9,
       22, 18, 11,  3, 25,  7,      15,  6, 26, 19, 12,  1,
       40, 51, 30, 36, 46, 54,      29, 39, 50, 44, 32, 47,
       43, 48, 38, 55, 33, 52,      45, 41, 49, 35, 28, 31 };
 
void deskey(unsigned char *key, short edf)  {
  /* Thanks to James Gillogly & Phil Karn! */
  register int i, j, l, m, n;
  unsigned char pc1m[56], pcr[56];
  unsigned long kn[32];
 
  for ( j = 0; j < 56; j++ ) {
    l = pc1[j];
    m = l & 07;
    pc1m[j] = (key[l >> 3] & bytebit[m]) ? 1 : 0;
  }
  for( i = 0; i < 16; i++ ) {
    if( edf == DE1 ) m = (15 - i) << 1;
    else             m = i << 1;
    n = m + 1;
    kn[m] = kn[n] = 0L;
    for( j = 0; j < 28; j++ ) {
      l = j + totrot;
      if( l < 28 ) pcr[j] = pc1m[l];
      else pcr[j] = pc1m[l - 28];
    }
    for( j = 28; j < 56; j++ ) {
      l = j + totrot;
      if( l < 56 ) pcr[j] = pc1m[l];
      else         pcr[j] = pc1m[l - 28];
    }
    for( j = 0; j < 24; j++ ) {
      if( pcr[pc2[j]] )    kn[m] |= bigbyte[j];
      if( pcr[pc2[j+24]] ) kn[n] |= bigbyte[j];
    }
  }
  cookey(kn);
}
 
static void cookey(unsigned long *raw1)  {
  register unsigned long *cook, *raw0;
  unsigned long dough[32];
  register int i;
 
  cook = dough;
  for( i = 0; i < 16; i++, raw1++ ) {
    raw0 = raw1++;
    *cook   = (*raw0 & 0x00fc0000L) << 6;
    *cook  |= (*raw0 & 0x00000fc0L) << 10;
    *cook  |= (*raw1 & 0x00fc0000L) >> 10;
    *cook++|= (*raw1 & 0x00000fc0L) >> 6;
    *cook   = (*raw0 & 0x0003f000L) << 12;
    *cook  |= (*raw0 & 0x0000003fL) << 16;
    *cook  |= (*raw1 & 0x0003f000L) >> 4;
    *cook++       |= (*raw1 & 0x0000003fL);
  }
  usekey(dough);
}
 
void cpkey(unsigned long *into)  {
  register unsigned long *from, *endp;
 
  from = KnL, endp = &KnL[32];
  while( from < endp ) *into++ = *from++;
}
 
void usekey(unsigned long *from)  {
  register unsigned long *to, *endp;
 
  to = KnL, endp = &KnL[32];
  while( to < endp ) *to++ = *from++;
}
 
#if 0
void des(unsigned char *inblock, unsigned char *outblock)  {
  unsigned long work[2];
 
  scrunch(inblock, work);
  desfunc(work, KnL);
  unscrun(work, outblock);
}
#endif
 
static void scrunch(unsigned char *outof, unsigned long *into)  {
  *into   = (*outof++ & 0xffL) << 24;
  *into  |= (*outof++ & 0xffL) << 16;
  *into  |= (*outof++ & 0xffL) << 8;
  *into++ |= (*outof++ & 0xffL);
  *into   = (*outof++ & 0xffL) << 24;
  *into  |= (*outof++ & 0xffL) << 16;
  *into  |= (*outof++ & 0xffL) << 8;
  *into  |= (*outof   & 0xffL);
}
 
static void unscrun(unsigned long *outof, unsigned char *into)  {
  *into++ = (*outof >> 24) & 0xffL;
  *into++ = (*outof >> 16) & 0xffL;
  *into++ = (*outof >>  8) & 0xffL;
  *into++ =  *outof++      & 0xffL;
  *into++ = (*outof >> 24) & 0xffL;
  *into++ = (*outof >> 16) & 0xffL;
  *into++ = (*outof >>  8) & 0xffL;
  *into   =  *outof     & 0xffL;
}
 
static unsigned long SP1[64] = {
  0x01010400L, 0x00000000L, 0x00010000L, 0x01010404L,
  0x01010004L, 0x00010404L, 0x00000004L, 0x00010000L,
  0x00000400L, 0x01010400L, 0x01010404L, 0x00000400L,
  0x01000404L, 0x01010004L, 0x01000000L, 0x00000004L,
  0x00000404L, 0x01000400L, 0x01000400L, 0x00010400L,
  0x00010400L, 0x01010000L, 0x01010000L, 0x01000404L,
  0x00010004L, 0x01000004L, 0x01000004L, 0x00010004L,
  0x00000000L, 0x00000404L, 0x00010404L, 0x01000000L,
  0x00010000L, 0x01010404L, 0x00000004L, 0x01010000L,
  0x01010400L, 0x01000000L, 0x01000000L, 0x00000400L,
  0x01010004L, 0x00010000L, 0x00010400L, 0x01000004L,
  0x00000400L, 0x00000004L, 0x01000404L, 0x00010404L,
  0x01010404L, 0x00010004L, 0x01010000L, 0x01000404L,
  0x01000004L, 0x00000404L, 0x00010404L, 0x01010400L,
  0x00000404L, 0x01000400L, 0x01000400L, 0x00000000L,
  0x00010004L, 0x00010400L, 0x00000000L, 0x01010004L };
 
static unsigned long SP2[64] = {аналог. таблица};
 
static unsigned long SP3[64] = {аналог. таблица};
 
static unsigned long SP4[64] = {аналог. таблица};
 
static unsigned long SP5[64] = {аналог. таблица};
 
static unsigned long SP6[64] = {аналог. таблица};
 
static unsigned long SP7[64] = {аналог. таблица};
 
static unsigned long SP8[64] = {аналог. таблица};
 
static void desfunc(unsigned long *block, unsigned long *keys)  {
  register unsigned long fval, work, right, leftt;
  register int round;
 
  leftt = block[0];
  right = block[1];
  work = ((leftt >> 4) ^ right) & 0x0f0f0f0fL;
  right ^= work;
  leftt ^= (work << 4);
  work = ((leftt >> 16) ^ right) & 0x0000ffffL;
  right ^= work;
  leftt ^= (work << 16);
  work = ((right >> 2) ^ leftt) & 0x33333333L;
  leftt ^= work;
  right ^= (work << 2);
  work = ((right >> 8) ^ leftt) & 0x00ff00ffL;
  leftt ^= work;
  right ^= (work << 8);
  right = ((right << 1) | ((right >> 31) & 1L)) & 0xffffffffL;
  work = (leftt ^ right) & 0xaaaaaaaaL;
  leftt ^= work;
  right ^= work;
  leftt = ((leftt << 1) | ((leftt >> 31) & 1L)) & 0xffffffffL;
 
  for( round = 0; round < 8; round++ ) {
    work  = (right << 28) | (right >> 4);
    work ^= *keys++;
    fval  = SP7[ work             & 0x3fL];
    fval |= SP5[(work >>  8) & 0x3fL];
    fval |= SP3[(work >> 16) & 0x3fL];
    fval |= SP1[(work >> 24) & 0x3fL];
    work  = right ^ *keys++;
    fval |= SP8[ work             & 0x3fL];
    fval |= SP6[(work >>  8) & 0x3fL];
    fval |= SP4[(work >> 16) & 0x3fL];
    fval |= SP2[(work >> 24) & 0x3fL];
    leftt ^= fval;
    work  = (leftt << 28) | (leftt >> 4);
    work ^= *keys++;
    fval  = SP7[ work             & 0x3fL];
    fval |= SP5[(work >>  8) & 0x3fL];
    fval |= SP3[(work >> 16) & 0x3fL];
    fval |= SP1[(work >> 24) & 0x3fL];
    work  = leftt ^ *keys++;
    fval |= SP8[ work             & 0x3fL];
    fval |= SP6[(work >>  8) & 0x3fL];
    fval |= SP4[(work >> 16) & 0x3fL];
    fval |= SP2[(work >> 24) & 0x3fL];
    right ^= fval;
  }
 
  right = (right << 31) | (right >> 1);
  work = (leftt ^ right) & 0xaaaaaaaaL;
  leftt ^= work;
  right ^= work;
  leftt = (leftt << 31) | (leftt >> 1);
  work = ((leftt >> 8) ^ right) & 0x00ff00ffL;
  right ^= work;
  leftt ^= (work << 8);
  work = ((leftt >> 2) ^ right) & 0x33333333L;
  right ^= work;
  leftt ^= (work << 2);
  work = ((right >> 16) ^ leftt) & 0x0000ffffL;
  leftt ^= work;
  right ^= (work << 16);
  work = ((right >> 4) ^ leftt) & 0x0f0f0f0fL;
  leftt ^= work;
  right ^= (work << 4);
  *block++ = right;
  *block = leftt;
}
 
 
 
void des_key(des_ctx *dc, unsigned char *key){
  deskey(key,EN0);
  cpkey(dc->ek);
  deskey(key,DE1);
  cpkey(dc->dk);
}
 
/* Encrypt several blocks in ECB mode.  Caller is responsible for
   short blocks. */
void des_enc(des_ctx *dc, unsigned char *Data, int blocks){
  unsigned long work[2];
  int i;
  unsigned char *cp;
 
  cp = Data;
  for(i=0;i<blocks;i++){
    scrunch(cp,work);
    desfunc(work,dc->ek);
    unscrun(work,cp);
    cp+=8;
  }
}
 
void des_dec(des_ctx *dc, unsigned char *Data, int blocks){
  unsigned long work[2];
  int i;
  unsigned char *cp;
 
  cp = Data;
  for(i=0;i<blocks;i++){
    scrunch(cp,work);
    desfunc(work,dc->dk);
    unscrun(work,cp);
    cp+=8;
  }
}
 
void main(void){
  des_ctx dc;
  int i;
  unsigned long Data;
  char *cp,key[8];
  cout<<"\nVvedite key: ";
  for (i=0;i<8;i++) cin>>key;
  cout<<"\nVvedite text: ";
  cin >> cp;
  unsigned int   lVal;
  lVal = strlen(cp) % 8;
  if (lVal != 0) Data= strlen(cp) + 8 - lVal;
  else Data=strlen(cp);
  char x[Data];
  x =cp;
 
  des_key(&dc,key);
 
  for (i=0;i<strlen(x)/8;i++) des_enc(&dc,x,i);
  cout<<"\nEncrypt text:";
  cout<<x;
  for (i=0;i<strlen(x)/8;i++)  des_dec(&dc,x,i);
  cout<<"\nDecrypt text:";
  cout<<x;
  while (1);
 
}
И еще, код выдает ошибку:

F:\Program Files\Microsoft Visual Studio\MyProjects\ex\forum(shnaier).cpp(5) : fatal error C1083: Cannot open include file: 'сstring.h': No such file or directory

пыталась найти в нете этот заголовочный файлик - безрезультатно....
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
27.03.2008, 18:21
Ответы с готовыми решениями:

Разобраться с конкретной реализацией бинарного дерева
Деревья тут обсуждаются часто. Перечитал много топиков. Количество вопросов только увеличилось. ...

Помогите с реализацией
На сервере(MS SQL 2000)есть таблица препараты с полями:наименование,код аптеки,цена,наличие...

Помогите с реализацией Alarm-ов
Добрый день уважаемые прошу помощи: Необходимо закинуть напоминание в почтовый ящик пользователя...

Помогите с реализацией архивирования
Добрый день. Следующая проблема. Есть база данных на сервере с дизайном для ввода и редактирования...

18
0 / 0 / 1
Регистрация: 27.03.2008
Сообщений: 75
28.03.2008, 17:30  [ТС] 2
написала в итоге эти заголовки так:

C++
1
2
#include <iostream.h>
#include <string.h>
выдает ошибки:

XML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
Compiling...
des.c
F:\Program Files\Microsoft Visual Studio\MyProjects\1\des.c(73) : warning C4047: '=' : 'int ' differs in levels of indirection from 'unsigned char *'
F:\Program Files\Microsoft Visual Studio\MyProjects\1\des.c(78) : warning C4047: '=' : 'int ' differs in levels of indirection from 'unsigned char *'
F:\Program Files\Microsoft Visual Studio\MyProjects\1\des.c(146) : warning C4244: '=' : conversion from 'unsigned long ' to 'unsigned char ', possible loss of data
F:\Program Files\Microsoft Visual Studio\MyProjects\1\des.c(147) : warning C4244: '=' : conversion from 'unsigned long ' to 'unsigned char ', possible loss of data
F:\Program Files\Microsoft Visual Studio\MyProjects\1\des.c(148) : warning C4244: '=' : conversion from 'unsigned long ' to 'unsigned char ', possible loss of data
F:\Program Files\Microsoft Visual Studio\MyProjects\1\des.c(149) : warning C4244: '=' : conversion from 'unsigned long ' to 'unsigned char ', possible loss of data
F:\Program Files\Microsoft Visual Studio\MyProjects\1\des.c(150) : warning C4244: '=' : conversion from 'unsigned long ' to 'unsigned char ', possible loss of data
F:\Program Files\Microsoft Visual Studio\MyProjects\1\des.c(151) : warning C4244: '=' : conversion from 'unsigned long ' to 'unsigned char ', possible loss of data
F:\Program Files\Microsoft Visual Studio\MyProjects\1\des.c(152) : warning C4244: '=' : conversion from 'unsigned long ' to 'unsigned char ', possible loss of data
F:\Program Files\Microsoft Visual Studio\MyProjects\1\des.c(153) : warning C4244: '=' : conversion from 'unsigned long ' to 'unsigned char ', possible loss of data
F:\Program Files\Microsoft Visual Studio\MyProjects\1\des.c(416) : error C2065: 'cout' : undeclared identifier
F:\Program Files\Microsoft Visual Studio\MyProjects\1\des.c(416) : error C2297: '<<' : illegal, right operand has type 'char [15]'
F:\Program Files\Microsoft Visual Studio\MyProjects\1\des.c(417) : error C2065: 'cin' : undeclared identifier
F:\Program Files\Microsoft Visual Studio\MyProjects\1\des.c(417) : error C2297: '>>' : illegal, right operand has type 'char [8]'
F:\Program Files\Microsoft Visual Studio\MyProjects\1\des.c(418) : error C2297: '<<' : illegal, right operand has type 'char [16]'
F:\Program Files\Microsoft Visual Studio\MyProjects\1\des.c(419) : error C2297: '>>' : illegal, right operand has type 'char *'
F:\Program Files\Microsoft Visual Studio\MyProjects\1\des.c(420) : error C2143: syntax error : missing ';' before 'type'
F:\Program Files\Microsoft Visual Studio\MyProjects\1\des.c(421) : error C2065: 'lVal' : undeclared identifier
F:\Program Files\Microsoft Visual Studio\MyProjects\1\des.c(424) : error C2143: syntax error : missing ';' before 'type'
F:\Program Files\Microsoft Visual Studio\MyProjects\1\des.c(425) : error C2065: 'x' : undeclared identifier
F:\Program Files\Microsoft Visual Studio\MyProjects\1\des.c(425) : warning C4047: '=' : 'int ' differs in levels of indirection from 'char *'
F:\Program Files\Microsoft Visual Studio\MyProjects\1\des.c(429) : warning C4047: 'function' : 'const char *' differs in levels of indirection from 'int '
F:\Program Files\Microsoft Visual Studio\MyProjects\1\des.c(429) : warning C4024: 'strlen' : different types for formal and actual parameter 1
F:\Program Files\Microsoft Visual Studio\MyProjects\1\des.c(429) : warning C4018: '<' : signed/unsigned mismatch
F:\Program Files\Microsoft Visual Studio\MyProjects\1\des.c(429) : warning C4047: 'function' : 'unsigned char *' differs in levels of indirection from 'int '
F:\Program Files\Microsoft Visual Studio\MyProjects\1\des.c(429) : warning C4024: 'des_enc' : different types for formal and actual parameter 2
F:\Program Files\Microsoft Visual Studio\MyProjects\1\des.c(430) : error C2297: '<<' : illegal, right operand has type 'char [15]'
F:\Program Files\Microsoft Visual Studio\MyProjects\1\des.c(431) : warning C4552: '<<' : operator has no effect; expected operator with side-effect
F:\Program Files\Microsoft Visual Studio\MyProjects\1\des.c(432) : warning C4047: 'function' : 'const char *' differs in levels of indirection from 'int '
F:\Program Files\Microsoft Visual Studio\MyProjects\1\des.c(432) : warning C4024: 'strlen' : different types for formal and actual parameter 1
F:\Program Files\Microsoft Visual Studio\MyProjects\1\des.c(432) : warning C4018: '<' : signed/unsigned mismatch
F:\Program Files\Microsoft Visual Studio\MyProjects\1\des.c(432) : warning C4047: 'function' : 'unsigned char *' differs in levels of indirection from 'int '
F:\Program Files\Microsoft Visual Studio\MyProjects\1\des.c(432) : warning C4024: 'des_dec' : different types for formal and actual parameter 2
F:\Program Files\Microsoft Visual Studio\MyProjects\1\des.c(433) : error C2297: '<<' : illegal, right operand has type 'char [15]'
F:\Program Files\Microsoft Visual Studio\MyProjects\1\des.c(434) : warning C4552: '<<' : operator has no effect; expected operator with side-effect
Error executing cl.exe.

des.exe - 12 error(s), 23 warning(s)
C++
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
 void main(void){
 des_ctx dc;
 int i;
 unsigned long Data;
 char *cp,key[8];
 cout<<"\nVvedite key: ";
 for (i=0;i<8;i++) cin>>key;
 cout<<"\nVvedite text: ";
 cin >> cp;
 unsigned int lVal;
 lVal = strlen(cp) % 8;
 if (lVal != 0) Data= strlen(cp) + 8 - lVal;
 else Data=strlen(cp);
 char x[Data];
 x =cp;
 
 des_key(&dc,key);
 
 for (i=0;i<strlen(x)/8;i++) des_enc(&dc,x,i);
 cout<<"\nEncrypt text:";
 cout<<x;
 for (i=0;i<strlen(x)/8;i++) des_dec(&dc,x,i);
 cout<<"\nDecrypt text:";
 cout<<x;
 while (1);
 
}
Что с этим делать? :fool:
Помогите исправить, пожалуйста!!!!
0
Флудер
195 / 33 / 11
Регистрация: 23.03.2007
Сообщений: 334
28.03.2008, 17:48 3
для использования cin\cout необходимо
#include <iostream.h>
0
0 / 0 / 1
Регистрация: 27.03.2008
Сообщений: 75
28.03.2008, 18:14  [ТС] 4
ну так у меня же этот заголовок подключен...не понимаю?
0
10 / 3 / 7
Регистрация: 25.03.2008
Сообщений: 50
29.03.2008, 18:20 5
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
#define EN0 0 /* MODE == encrypt */
#define DE1 1 /* MODE == decrypt */
#include <iostream>
#include <string.h>
using namespace std;
typedef struct
{
    unsigned long ek[32];
    unsigned long dk[32];
} des_ctx;
extern void deskey(unsigned char *, short);
extern void usekey(unsigned long *);
extern void cpkey(unsigned long *);
extern void des(unsigned char *, unsigned char *);
static void scrunch(unsigned char *, unsigned long *);
static void unscrun(unsigned long *, unsigned char *);
static void desfunc(unsigned long *, unsigned long *);
static void cookey(unsigned long *);
static unsigned long KnL[32] = { 0L };
static unsigned long KnR[32] = { 0L };
static unsigned long Kn3[32] = { 0L };
static unsigned char Df_Key[24] =
{
    0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef,
    0xfe,0xdc,0xba,0x98,0x76,0x54,0x32,0x10,
    0x89,0xab,0xcd,0xef,0x01,0x23,0x45,0x67
};
static unsigned short bytebit[8] =
{
    0200, 0100, 040, 020, 010, 04, 02, 01
};
static unsigned long bigbyte[24] =
{
    0x800000L, 0x400000L, 0x200000L, 0x100000L,
    0x80000L, 0x40000L, 0x20000L, 0x10000L,
    0x8000L, 0x4000L, 0x2000L, 0x1000L,
    0x800L, 0x400L, 0x200L, 0x100L,
    0x80L, 0x40L, 0x20L, 0x10L,
    0x8L, 0x4L, 0x2L, 0x1L
};
 
static unsigned char pc1[56] =
{
    56, 48, 40, 32, 24, 16, 8, 0, 57, 49, 41, 33, 25, 17,
    9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35,
    62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21,
    13, 5, 60, 52, 44, 36, 28, 20, 12, 4, 27, 19, 11, 3
};
static unsigned char totrot[16] =
{
    1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28
};
static unsigned char pc2[48] =
{
    13, 16, 10, 23, 0, 4, 2, 27, 14, 5, 20, 9,
    22, 18, 11, 3, 25, 7, 15, 6, 26, 19, 12, 1,
    40, 51, 30, 36, 46, 54, 29, 39, 50, 44, 32, 47,
    43, 48, 38, 55, 33, 52, 45, 41, 49, 35, 28, 31
};
void deskey(unsigned char *key, short edf)
{
    /* Thanks to James Gillogly & Phil Karn! */
    register int i, j, l, m, n;
    unsigned char pc1m[56], pcr[56];
    unsigned long kn[32];
    for ( j = 0; j < 56; j++ )
    {
        l = pc1[j];
        m = l & 07;
        pc1m[j] = (key[l >> 3] & bytebit[m]) ? 1 : 0;
    }
    for( i = 0; i < 16; i++ )
    {
        if( edf == DE1 ) m = (15 - i) << 1;
        else m = i << 1;
        n = m + 1;
        kn[m] = kn[n] = 0L;
        for( j = 0; j < 28; j++ )
        {
            l = j + totrot[j];
            if( l < 28 ) pcr[j] = pc1m[l];
            else pcr[j] = pc1m[l - 28];
        }
        for( j = 28; j < 56; j++ )
        {
            l = j + totrot[j];
            if( l < 56 ) pcr[j] = pc1m[l];
            else pcr[j] = pc1m[l - 28];
        }
        for( j = 0; j < 24; j++ )
        {
            if( pcr[pc2[j]] ) kn[m] |= bigbyte[j];
            if( pcr[pc2[j+24]] ) kn[n] |= bigbyte[j];
        }
    }
    cookey(kn);
}
static void cookey(unsigned long *raw1)
{
    register unsigned long *cook, *raw0;
    unsigned long dough[32];
    register int i;
    cook = dough;
    for( i = 0; i < 16; i++, raw1++ )
    {
        raw0 = raw1++;
        *cook = (*raw0 & 0x00fc0000L) << 6;
        *cook |= (*raw0 & 0x00000fc0L) << 10;
        *cook |= (*raw1 & 0x00fc0000L) >> 10;
        *cook++|= (*raw1 & 0x00000fc0L) >> 6;
        *cook = (*raw0 & 0x0003f000L) << 12;
        *cook |= (*raw0 & 0x0000003fL) << 16;
        *cook |= (*raw1 & 0x0003f000L) >> 4;
        *cook++ |= (*raw1 & 0x0000003fL);
    }
    usekey(dough);
}
void cpkey(unsigned long *into)
{
    register unsigned long *from, *endp;
    from = KnL, endp = &KnL[32];
    while( from < endp ) *into++ = *from++;
}
void usekey(unsigned long *from)
{
    register unsigned long *to, *endp;
    to = KnL, endp = &KnL[32];
    while( to < endp ) *to++ = *from++;
}
#if 0
void des(unsigned char *inblock, unsigned char *outblock)
{
    unsigned long work[2];
    scrunch(inblock, work);
    desfunc(work, KnL);
    unscrun(work, outblock);
}
#endif
static void scrunch(unsigned char *outof, unsigned long *into)
{
    *into = (*outof++ & 0xffL) << 24;
    *into |= (*outof++ & 0xffL) << 16;
    *into |= (*outof++ & 0xffL) << 8;
    *into++ |= (*outof++ & 0xffL);
    *into = (*outof++ & 0xffL) << 24;
    *into |= (*outof++ & 0xffL) << 16;
    *into |= (*outof++ & 0xffL) << 8;
    *into |= (*outof & 0xffL);
}
static void unscrun(unsigned long *outof, unsigned char *into)
{
    *into++ = (*outof >> 24) & 0xffL;
    *into++ = (*outof >> 16) & 0xffL;
    *into++ = (*outof >> 8) & 0xffL;
    *into++ = *outof++ & 0xffL;
    *into++ = (*outof >> 24) & 0xffL;
    *into++ = (*outof >> 16) & 0xffL;
    *into++ = (*outof >> 8) & 0xffL;
    *into = *outof & 0xffL;
}
static unsigned long SP1[64] =
{
    0x01010400L, 0x00000000L, 0x00010000L, 0x01010404L,
    0x01010004L, 0x00010404L, 0x00000004L, 0x00010000L,
    0x00000400L, 0x01010400L, 0x01010404L, 0x00000400L,
    0x01000404L, 0x01010004L, 0x01000000L, 0x00000004L,
    0x00000404L, 0x01000400L, 0x01000400L, 0x00010400L,
    0x00010400L, 0x01010000L, 0x01010000L, 0x01000404L,
    0x00010004L, 0x01000004L, 0x01000004L, 0x00010004L,
    0x00000000L, 0x00000404L, 0x00010404L, 0x01000000L,
    0x00010000L, 0x01010404L, 0x00000004L, 0x01010000L,
    0x01010400L, 0x01000000L, 0x01000000L, 0x00000400L,
    0x01010004L, 0x00010000L, 0x00010400L, 0x01000004L,
    0x00000400L, 0x00000004L, 0x01000404L, 0x00010404L,
    0x01010404L, 0x00010004L, 0x01010000L, 0x01000404L,
    0x01000004L, 0x00000404L, 0x00010404L, 0x01010400L,
    0x00000404L, 0x01000400L, 0x01000400L, 0x00000000L,
    0x00010004L, 0x00010400L, 0x00000000L, 0x01010004L
};
static unsigned long SP2[64];
static unsigned long SP3[64];
static unsigned long SP4[64];
static unsigned long SP5[64];
static unsigned long SP6[64];
static unsigned long SP7[64];
static unsigned long SP8[64];
static void desfunc(unsigned long *block, unsigned long *keys)
{
    register unsigned long fval, work, right, leftt;
    register int round;
    leftt = block[0];
    right = block[1];
    work = ((leftt >> 4) ^ right) & 0x0f0f0f0fL;
    right ^= work;
    leftt ^= (work << 4);
    work = ((leftt >> 16) ^ right) & 0x0000ffffL;
    right ^= work;
    leftt ^= (work << 16);
    work = ((right >> 2) ^ leftt) & 0x33333333L;
    leftt ^= work;
    right ^= (work << 2);
    work = ((right >> 8) ^ leftt) & 0x00ff00ffL;
    leftt ^= work;
    right ^= (work << 8);
    right = ((right << 1) | ((right >> 31) & 1L)) & 0xffffffffL;
    work = (leftt ^ right) & 0xaaaaaaaaL;
    leftt ^= work;
    right ^= work;
    leftt = ((leftt << 1) | ((leftt >> 31) & 1L)) & 0xffffffffL;
    for( round = 0; round < 8; round++ )
    {
        work = (right << 28) | (right >> 4);
        work ^= *keys++;
        fval = SP7[ work & 0x3fL];
        fval |= SP5[(work >> 8) & 0x3fL];
        fval |= SP3[(work >> 16) & 0x3fL];
        fval |= SP1[(work >> 24) & 0x3fL];
        work = right ^ *keys++;
        fval |= SP8[ work & 0x3fL];
        fval |= SP6[(work >> 8) & 0x3fL];
        fval |= SP4[(work >> 16) & 0x3fL];
        fval |= SP2[(work >> 24) & 0x3fL];
        leftt ^= fval;
        work = (leftt << 28) | (leftt >> 4);
        work ^= *keys++;
        fval = SP7[ work & 0x3fL];
        fval |= SP5[(work >> 8) & 0x3fL];
        fval |= SP3[(work >> 16) & 0x3fL];
        fval |= SP1[(work >> 24) & 0x3fL];
        work = leftt ^ *keys++;
        fval |= SP8[ work & 0x3fL];
        fval |= SP6[(work >> 8) & 0x3fL];
        fval |= SP4[(work >> 16) & 0x3fL];
        fval |= SP2[(work >> 24) & 0x3fL];
        right ^= fval;
    }
    right = (right << 31) | (right >> 1);
    work = (leftt ^ right) & 0xaaaaaaaaL;
    leftt ^= work;
    right ^= work;
    leftt = (leftt << 31) | (leftt >> 1);
    work = ((leftt >> 8) ^ right) & 0x00ff00ffL;
    right ^= work;
    leftt ^= (work << 8);
    work = ((leftt >> 2) ^ right) & 0x33333333L;
    right ^= work;
    leftt ^= (work << 2);
    work = ((right >> 16) ^ leftt) & 0x0000ffffL;
    leftt ^= work;
    right ^= (work << 16);
    work = ((right >> 4) ^ leftt) & 0x0f0f0f0fL;
    leftt ^= work;
    right ^= (work << 4);
    *block++ = right;
    *block = leftt;
}
 
 
void des_key(des_ctx *dc, unsigned char *key)
{
    deskey(key,EN0);
    cpkey(dc->ek);
    deskey(key,DE1);
    cpkey(dc->dk);
}
/* Encrypt several blocks in ECB mode. Caller is responsible for
short blocks. */
void des_enc(des_ctx *dc, unsigned char *Data, int blocks)
{
    unsigned long work[2];
    int i;
    unsigned char *cp;
    cp = Data;
    for(i=0; i<blocks; i++)
    {
        scrunch(cp,work);
        desfunc(work,dc->ek);
        unscrun(work,cp);
        cp+=8;
    }
}
void des_dec(des_ctx *dc, unsigned char *Data, int blocks)
{
    unsigned long work[2];
    int i;
    unsigned char *cp;
    cp = Data;
    for(i=0; i<blocks; i++)
    {
        scrunch(cp,work);
        desfunc(work,dc->dk);
        unscrun(work,cp);
        cp+=8;
    }
}
void main(void)
{
    des_ctx dc;
    int i;
    unsigned long Data;
    char cp[256], key[8];
    cout<<"\nVvedite key: ";
    for (i=0; i<8; i++) cin>>key;
    cout<<"\nVvedite text: ";
    cin >> *cp;
    unsigned int lVal;
    lVal = strlen(cp) % 8;
    if (lVal != 0) Data= strlen(cp) + 8 - lVal;
    else int Data=strlen(cp);
    char *x;
    x=new char[Data+1];
    strcpy(x,cp);
    des_key(&dc,(unsigned char*)key);
    for (i=0; i<strlen(x)/8; i++) des_enc(&dc,(unsigned char*)x,i);
    cout<<"\nEncrypt text:";
    cout<<x;
    for (i=0; i<strlen(x)/8; i++) des_dec(&dc,(unsigned char*)x,i);
    cout<<"\nDecrypt text:";
    cout<<x;
    while (1);
    delete [] x;
}
Вообщем я ошибки исправил, предупреждения остались ну и лям с ними, но более неадекватного кода я не видел!!!
0
0 / 0 / 1
Регистрация: 27.03.2008
Сообщений: 75
31.03.2008, 10:12  [ТС] 6
SVEN - спасибо огромное!!! А что в этом коде неадекватного? Это ж из Шнайера?
0
10 / 3 / 7
Регистрация: 25.03.2008
Сообщений: 50
31.03.2008, 15:42 7
Просто, по-моему, в объектах этот код выглядел бы лаконичней, понятней и более удобочитаемым!?
0
0 / 0 / 1
Регистрация: 27.03.2008
Сообщений: 75
31.03.2008, 17:52  [ТС] 8
Возможно у Вас есть какие-то более оптимальные версии реализации этого алгоритма, которыми Вы могли бы поделиться?
0
Администратор
83610 / 52188 / 244
Регистрация: 10.04.2006
Сообщений: 13,425
31.03.2008, 17:55 9
Способ 1.

des.cpp
Код
#include <stdio.h>

#include "des.hpp"
#include "dessboxes.inc"

Word wMask[] = { 1, 1, 3, 3, 3, 3, 3, 3,
				 1, 3, 3, 3, 3, 3, 3, 1 };

Byte bShift[] = { 1, 1, 2, 2, 2, 2, 2, 2,
				  1, 2, 2, 2, 2, 2, 2, 1 };

// Table for key permutation
Byte bPC1[] = { 56, 48, 40, 32, 24, 16,  8,
				 0, 57, 49, 41, 33, 25, 17,
				 9,  1, 58, 50, 42, 34, 26,
				18, 10,  2, 59, 51, 43, 35,
				62, 54, 46, 38, 30, 22, 14,
				 6, 61, 53, 45, 37, 29, 21,
				13,  5, 60, 52, 44, 36, 28,
				20, 12,  4, 27, 19, 11,  3 };

// Table for compression permutation
Byte bPC2[] = { 13, 16, 10, 23,  0,  4,
				 2, 27, 14,  5, 20,  9,
				22, 18, 11,  3, 25,  7,
				15,  6, 26, 19, 12,  1,
				40, 51, 30, 36, 46, 54,
				29, 39, 50, 44, 32, 47,
				43, 48, 38, 55, 33, 52,
				45, 41, 49, 35, 28, 31 };

// Table for initial permutation IP
Byte bIP1[] = { 57, 49, 41, 33, 25, 17,  9,  1,
				59, 51, 43, 35, 27, 19, 11,  3,
				61, 53, 45, 37, 29, 21, 13,  5,
				63, 55, 47, 39, 31, 23, 15,  7,
				56, 48, 40, 32, 24, 16,  8,  0,
				58, 50, 42, 34, 26, 18, 10,  2,
				60, 52, 44, 36, 28, 20, 12,  4,
				62, 54, 46, 38, 30, 22, 14,  6 };

//                               -1
// Table for final permutation IP
Byte bIP2[] = { 39,  7, 47, 15, 55, 23, 63, 31,
				38,  6, 46, 14, 54, 22, 62, 30,
				37,  5, 45, 13, 53, 21, 61, 29,
				36,  4, 44, 12, 52, 20, 60, 28,
				35,  3, 43, 11, 51, 19, 59, 27,
				34,  2, 42, 10, 50, 18, 58, 26,
				33,  1, 41,  9, 49, 17, 57, 25,
				32,  0, 40,  8, 48, 16, 56, 24 };

// Table for expansion permutation
Byte bE[] = { 31,  0,  1,  2,  3,  4,
			   3,  4,  5,  6,  7,  8,
			   7,  8,  9, 10, 11, 12,
			  11, 12, 13, 14, 15, 16,
			  15, 16, 17, 18, 19, 20,
			  19, 20, 21, 22, 23, 24,
			  23, 24, 25, 26, 27, 28,
			  27, 28, 29, 30, 31,  0 };

// Table for P-Box permutation
Byte bP[] = { 15,  6, 19, 20, 28, 11, 27, 16,
			   0, 14, 22, 25,  4, 17, 30,  9,
			   1,  7, 23, 13, 31, 26,  2,  8,
			  18, 12, 29,  5, 21, 10,  3, 24 };

CDESKey::CDESKey()
{
}

CDESKey::CDESKey(const CDESKey &cDESKey)
{
	dwMaster = cDESKey.dwMaster;
	MakeKeys();
}

CDESKey::CDESKey(const Byte *pbMaster, Word wKeySize)
{
	Dword dwDESKey = DWORDCONST(0);
	memcpy(&dwDESKey, pbMaster, wKeySize);
	dwDESKey = REVERSEDWORD(dwDESKey);
	MIRROR(dwDESKey, 64, dwMaster);
	MakeKeys();
	dwDESKey = 0;
}

CDESKey::CDESKey(Dword dwDESKey)
{
	MIRROR(dwDESKey, 64, dwMaster);
	MakeKeys();
	dwDESKey = 0;								// Cleanup
}

CDESKey::~CDESKey()
{
	for (int i = 0; i < 16; i++)			// Cleanup
		dwKey[i] = 0;
	dwMaster = 0;
}

void CDESKey::MakeKeys()
{
	Dword c = 0;
	Dword d = 0;
	for (int k = 0; k < 28; k++) {
		PUTBIT(c, k, GETBIT(dwMaster, bPC1[k]));
		PUTBIT(d, k, GETBIT(dwMaster, bPC1[k + 28]));
	}
	for (int q = 0; q < 16; q++) {
		c = (c >> bShift[q]) | ((c & wMask[q]) << (28 - bShift[q]));
		d = (d >> bShift[q]) | ((d & wMask[q]) << (28 - bShift[q]));
		Dword t = ((Dword)d << 28) | c;
		STIRBITS(t, 48, bPC2, dwKey[q]);
	}
	c = d = 0;									// Cleanup
}

CDESBlock::CDESBlock()
{
	dwData = 0;									// This is here for definiteness
}

CDESBlock::CDESBlock(const CDESBlock &cDESBlock)
{
	dwData = cDESBlock.dwData;
}

CDESBlock::CDESBlock(Dword dwValue)
{
	MIRROR(dwValue, 64, dwData);
}

CDESBlock::CDESBlock(const Byte *pbData, Word wLength)
{
	SetData(pbData, wLength);
}

CDESBlock::~CDESBlock()
{
	dwData = 0;									// Cleanup
}

void CDESBlock::Encrypt(const CDESKey &cDESKey)
{
	Crypt(cDESKey, false);
}

void CDESBlock::Decrypt(const CDESKey &cDESKey)
{
	Crypt(cDESKey, true);
}

// fgDirection: true = decrypt
//              false = encrypt
void CDESBlock::Crypt(const CDESKey &cDESKey, bool fgDirection)
{
	Dword a;
	Dword b;

	STIRBITS(dwData, 64, bIP1, a);
	Word r = HiWORD(a);
	Word l = LoWORD(a);
	Word s;
	for (int i = 0; i < 16; i++) {
		STIRBITS(r, 48, bE, a);
		if (fgDirection)
			b = a ^ cDESKey.GetKey(15 - i);
		else
			b = a ^ cDESKey.GetKey(i);
		a = 0;
		for (int j = 0; j < 8; j++) {
			a <<= 4;
			a |= bS[j][(b >> ((7 - j) * 6)) & 0x3f];
		}
		STIRBITS(a, 32, bP, b);
		
		s = r;
		r = l ^ LoWORD(b);
		l = s;
	}
	a = ((Dword)l << 32) | r;
	STIRBITS(a, 64, bIP2, dwData);
	a = b = l = r = 0;						// Cleanup
}

void CDESBlock::SetValue(Dword dwValue)
{
	MIRROR(dwValue, 64, dwData);
}

Dword CDESBlock::GetValue()
{
	MIRROR(dwData, 64, dwResult);
	return dwResult;						// It is normal to invoke this method
											// only for encrypted data, so we do
											// not need to clean the buffer variable.
}

void CDESBlock::SetData(const Byte *pbData, Word/* wLength*/)
{
	Dword dwValue = 0;
	memcpy(&dwValue, pbData, BLOCKSIZE);
	dwValue = REVERSEDWORD(dwValue);
	MIRROR(dwValue, 64, dwData);
	dwValue = 0;								// Cleanup
}

Byte *CDESBlock::GetData()
{
	MIRROR(dwData, 64, dwResult);
	dwResult = REVERSEDWORD(dwResult);
	return (Byte *)&dwResult;
}
des.hpp
Код
#ifndef __DES_HPP__
#define __DES_HPP__

#include <string.h>

#include "crypto.hpp"

class CDESKey
{
	public:
		enum { KEYSIZE = 8 };

	public:
		CDESKey();
		CDESKey(const CDESKey &);
		CDESKey(const Byte *, Word = KEYSIZE);
		CDESKey(Dword);
		virtual ~CDESKey();

	public:
		Dword GetMaster() const { return dwMaster; };
		Dword GetKey(Word i) const { return dwKey[i]; };

	public:
		Word GetKeySize() { return KEYSIZE; };

	private:
		void MakeKeys();

	private:
		Dword dwMaster;
		Dword dwKey[16];
};

class CDESBlock
{
	public:
		enum { BLOCKSIZE = 8 };

	public:
		CDESBlock();
		CDESBlock(const CDESBlock &);
		CDESBlock(Dword);
		CDESBlock(const Byte *, Word wLength = BLOCKSIZE);
		virtual ~CDESBlock();

	public:
		void Encrypt(const CDESKey &);
		void Decrypt(const CDESKey &);
		void SetData(const Byte *, Word = BLOCKSIZE);
		Byte *GetData();
		Word GetBlockSize() { return BLOCKSIZE; };
		void SetValue(Dword);
		Dword GetValue();
	
	protected:
		void Crypt(const CDESKey &, bool);

	private:
		Dword dwData, dwResult;
};

#endif // __DES_HPP__
dessboxes.inc
Код
// Automatically generated header.
// See "dessboxes.pl" for more information.
// Do not edit by hand.

#ifndef __DESSBOXES_HPP__
#define __DESSBOXES_HPP__

Byte bS[][64] =
{
	{
		11, 14,  5,  0,  6,  9, 10, 15,  1,  2, 12,  5, 13,  7,  3, 10, 
		 4, 13,  9,  6, 15,  3,  0, 12,  2,  8,  7, 11,  8,  4, 14,  1, 
		 8,  4,  3, 15,  5,  2,  0, 12, 11,  7,  6,  9, 14,  1,  9,  6, 
		15,  8, 10,  3, 12,  5,  7, 10,  1, 14, 13,  0,  2, 11,  4, 13
	},
	{
		 2,  8, 12,  5, 15,  3, 10,  0,  4, 13,  9,  6,  1, 14,  6,  9, 
		13,  2,  3, 15,  0, 12,  5, 10,  7, 11, 14,  1, 11,  7,  8,  4, 
		11,  6,  7,  9,  2,  8,  4,  7, 13, 11, 10,  0,  8,  5,  1, 12, 
		 0, 13, 12, 10,  9,  2, 15,  4, 14,  1,  3, 15,  5, 14,  6,  3
	},
	{
		 3,  9,  0, 14,  9,  4,  7,  8,  5, 15, 12,  2,  6,  3, 10, 13, 
		 8,  7, 11,  0,  4,  1, 14, 11, 15, 10,  2,  5,  1, 12, 13,  6, 
		 5,  2,  6, 13, 14,  9,  0,  6,  2,  4, 11,  8,  9, 15, 12,  1, 
		15, 12,  8,  7,  3, 10, 13,  0,  4,  3,  7, 14, 10,  5,  1, 11
	},
	{
		 4,  2,  1, 15, 14,  5, 11,  6,  2,  8, 12,  3, 13, 14,  7,  0, 
		 3,  4, 10,  9,  5, 11,  0, 12,  8, 13, 15, 10,  6,  1,  9,  7, 
		 7, 13, 10,  6,  2,  8, 12,  5,  4,  3, 15,  0, 11,  4,  1, 10, 
		13,  1,  0, 15, 14,  7,  9,  2,  3, 14,  5,  9,  8, 11,  6, 12
	},
	{
		14,  5,  8, 15,  0,  3, 13, 10,  7,  9,  1, 12,  9, 14,  2,  1, 
		11,  6,  4,  8,  6, 13,  3,  4, 12,  0, 10,  7,  5, 11, 15,  2, 
		11, 12,  2,  9,  6,  5,  8,  3, 13,  0,  4, 10,  0, 11,  7,  4, 
		 1, 15, 14,  2, 15,  8,  5, 14, 10,  6,  3, 13, 12,  1,  9,  7
	},
	{
		 5, 11,  8, 13,  6,  1, 13, 10,  9,  2,  3,  4, 15, 12,  4,  7, 
		 0,  6, 11,  8, 12, 15,  2,  5,  7,  9, 14,  3, 10,  0,  1, 14, 
		11,  8,  4,  2, 12,  6,  3, 13,  0, 11, 10,  7,  6,  1, 15,  4, 
		14,  5,  1, 15,  2,  9, 13, 10,  9,  0,  7, 12,  5, 14,  8,  3
	},
	{
		15,  0,  9, 10,  6,  5,  3,  9,  1, 14,  4,  3, 12, 11, 10,  4, 
		 8,  7, 14,  1, 13,  2,  0, 12,  7, 13, 11,  6,  2,  8,  5, 15, 
		12, 11,  3, 13, 15, 12,  6,  0,  2,  5,  8, 14,  1,  2, 13,  7, 
		11,  1,  0,  6,  4, 15,  9, 10, 14,  8,  5,  3,  7,  4, 10,  9
	},
	{
		 7,  2, 12, 15,  4, 11, 10, 12, 11,  7,  6,  9, 13,  4,  0, 10, 
		 2,  8,  5,  3, 15,  6,  9,  5,  8,  1,  3, 14,  1, 13, 14,  0, 
		 0, 15,  5, 10,  7,  2,  9,  5, 14,  1,  3, 12, 11,  8, 12,  6, 
		15,  3,  6, 13,  4,  9, 10,  0,  2,  4, 13,  7,  8, 14,  1, 11
	}
};

#endif // __DESSBOXES_HPP__
dessboxes.pl
Код
#!/usr/bin/perl -w

@s = ( 
		 [
			[ 14,  4, 13,  1,  2, 15, 11,  8,  3, 10,  6, 12,  5,  9,  0,  7 ],
		   [  0, 15,  7,  4, 14,  2, 13,  1, 10,  6, 12, 11,  9,  5,  3,  8 ],
		   [  4,  1, 14,  8, 13,  6,  2, 11, 15, 12,  9,  7,  3, 10,  5,  0 ],
		   [ 15, 12,  8,  2,  4,  9,  1,  7,  5, 11,  3, 14, 10,  0,  6, 13 ] 
		 ],
		 [
			[ 15,  1,  8, 14,  6, 11,  3,  4,  9,  7,  2, 13, 12,  0,  5, 10 ],
		   [  3, 13,  4,  7, 15,  2,  8, 14, 12,  0,  1, 10,  6,  9, 11,  5 ],
		   [  0, 14,  7, 11, 10,  4, 13,  1,  5,  8, 12,  6,  9,  3,  2, 15 ],
		   [ 13,  8, 10,  1,  3, 15,  4,  2, 11,  6,  7, 12,  0,  5, 14,  9 ] 
		 ],
		 [
			[ 10,  0,  9, 14,  6,  3, 15,  5,  1, 13, 12,  7, 11,  4,  2,  8 ],
		   [ 13,  7,  0,  9,  3,  4,  6, 10,  2,  8,  5, 14, 12, 11, 15,  1 ],
		   [ 13,  6,  4,  9,  8, 15,  3,  0, 11,  1,  2, 12,  5, 10, 14,  7 ],
		   [  1, 10, 13,  0,  6,  9,  8,  7,  4, 15, 14,  3, 11,  5,  2, 12 ] 
		 ],
		 [
			[  7, 13, 14,  3,  0,  6,  9, 10,  1,  2,  8,  5, 11, 12,  4, 15 ],
		   [ 13,  8, 11,  5,  6, 15,  0,  3,  4,  7,  2, 12,  1, 10, 14,  9 ],
		   [ 10,  6,  9,  0, 12, 11,  7, 13, 15,  1,  3, 14,  5,  2,  8,  4 ],
		   [  3, 15,  0,  6, 10,  1, 13,  8,  9,  4,  5, 11, 12,  7,  2, 14 ] 
		 ],
		 [
			[  2, 12,  4,  1,  7, 10, 11,  6,  8,  5,  3, 15, 13,  0, 14,  9 ],
		   [ 14, 11,  2, 12,  4,  7, 13,  1,  5,  0, 15, 10,  3,  9,  8,  6 ],
		   [  4,  2,  1, 11, 10, 13,  7,  8, 15,  9, 12,  5,  6,  3,  0, 14 ],
		   [ 11,  8, 12,  7,  1, 14,  2, 13,  6, 15,  0,  9, 10,  4,  5,  3 ] 
		 ],
		 [
			[ 12,  1, 10, 15,  9,  2,  6,  8,  0, 13,  3,  4, 14,  7,  5, 11 ],
		   [ 10, 15,  4,  2,  7, 12,  9,  5,  6,  1, 13, 14,  0, 11,  3,  8 ],
		   [  9, 14, 15,  5,  2,  8, 12,  3,  7,  0,  4, 10,  1, 13, 11,  6 ],
		   [  4,  3,  2, 12,  9,  5, 15, 10, 11, 14,  1,  7,  6,  0,  8, 13 ] 
		 ],
		 [
			[  4, 11,  2, 14, 15,  0,  8, 13,  3, 12,  9,  7,  5, 10,  6,  1 ],
		   [ 13,  0, 11,  7,  4,  9,  1, 10, 14,  3,  5, 12,  2, 15,  8,  6 ],
		   [  1,  4, 11, 13, 12,  3,  7, 14, 10, 15,  6,  8,  0,  5,  9,  2 ],
		   [  6, 11, 13,  8,  1,  4, 10,  7,  9,  5,  0, 15, 14,  2,  3, 12 ] 
		 ],
		 [
			[ 13,  2,  8,  4,  6, 15, 11,  1, 10,  9,  3, 14,  5,  0, 12,  7 ],
		   [  1, 15, 13,  8, 10,  3,  7,  4, 12,  5,  6, 11,  0, 14,  9,  2 ],
		   [  7, 11,  4,  1,  9, 12, 14,  2,  0,  6, 10, 13, 15,  3,  5,  8 ],
		   [  2,  1, 14,  7,  4, 10,  8, 13, 15, 12,  9,  0,  3,  5,  6, 11 ] 
		 ],
	 );

print <<EOT;
// Automatically generated header.
// See "dessboxes.pl" for more information.
// Do not edit by hand.

#ifndef __DESSBOXES_HPP__
#define __DESSBOXES_HPP__

Byte bS[][64] =
{
EOT
for (0 .. 7) {
	$sbox = 7 - $_;
	printf("\t{\n");
	for (0 .. 63) {
		$col = $_ >> 1;
		$col = (($col << 3) & 8) | 
				 (($col << 1) & 4) |
				 (($col >> 1) & 2) |
				 (($col >> 3) & 1);
		$row = (($_ >> 5) & 1) | (($_ << 1) & 2);
		$cell = $s[$sbox][$row][$col];
		
		printf("\t\t") if ($_ % 16 == 0);		
		printf("%2d", (($cell << 3) & 8) | (($cell << 1) & 4) | (($cell >> 1) & 2) | (($cell >> 3) & 1));
		printf(", ") if (($_ + 1) % 64 != 0);
		printf("\n") if (($_ + 1) % 16 == 0);
	}
	printf("\t},\n") if ($sbox != 0);
	printf("\t}\n") if ($sbox == 0);
}
print <<EOT;
};

#endif // __DESSBOXES_HPP__
EOT
crypto.hpp
Код
#ifndef __CRYPTO_HPP__
#define __CRYPTO_HPP__

#ifdef WIN32
#define DWORDCONST(x)				(x##i64)
#define WORDCONST(x)				(x##L)
#else
#define DWORDCONST(x)				(x##LL)
#define WORDCONST(x)				(x##L)
#endif

#define BASE						DWORDCONST(0x100000000)
#define ONE							DWORDCONST(0x1)
#define MaxWORD						WORDCONST(0xFFFFFFFF)

#ifdef WIN32
	typedef unsigned __int32		Word;
	typedef unsigned __int64		Dword;
#else
	typedef unsigned int			Word;
	typedef unsigned long long		Dword;
#endif

typedef unsigned char				Byte;
typedef unsigned short				Short;

#define CHARSINWORD							8
#define BITSINWORD						   32
#define BITSINSHORT						   16
#define BITSINBYTE							8
#define BYTESINWORD					(BITSINWORD / BITSINBYTE)
#define BYTESINSHORT				(BITSINSHORT / BITSINBYTE)

// Operations for all types
#define Max(a, b)					((a) > (b) ? (a) : (b))
#define Min(a, b)					((a) < (b) ? (a) : (b))

// Operations with DWORDs
#define HiWORD(a)					((Word)((a) >> BITSINWORD))
#define LoWORD(a)					((Word)(a))
#define DWSHORT0(a)					((Short)((a) >> 48))
#define DWSHORT1(a)					((Short)((a) >> 32))
#define DWSHORT2(a)					((Short)((a) >> 16))
#define DWSHORT3(a)					((Short)(a))
#define DWBYTE0(a)					((Byte)((a) >> 56))
#define DWBYTE1(a)					((Byte)((a) >> 48))
#define DWBYTE2(a)					((Byte)((a) >> 40))
#define DWBYTE3(a)					((Byte)((a) >> 32))
#define DWBYTE4(a)					((Byte)((a) >> 24))
#define DWBYTE5(a)					((Byte)((a) >> 16))
#define DWBYTE6(a)					((Byte)((a) >> 8))
#define DWBYTE7(a)					((Byte)(a))
#define MAKEDWORD(a, b, c, d)		(((Dword)(a) << 48) | ((Dword)(b) << 32) | ((Dword)(c) << 16) | (Dword)(d))
#define MAKEDWORDB(a, b, c, d, e, f, g, h) \
									(((Dword)(a) << 56) | ((Dword)(b) << 48) | ((Dword)(c) << 40) | ((Dword)(d) << 32) | \
									 ((Dword)(e) << 24) | ((Dword)(f) << 16) | ((Dword)(g) << 8) | (Dword)(h))
#define REVERSEDWORD(a)				(((Dword)REVERSEWORD(LoWORD(a)) << BITSINWORD) | (REVERSEWORD(HiWORD(a))))

// Operations with WORDs
// The oldest byte is 0 (leftmost)
// The youngest byte is 3 (rightmost)
#define HISHORT(a)					((Short)((a) >> BITSINSHORT))
#define LOSHORT(a)					((Short)(a))
#define WBYTE0(a)					((Byte)((a) >> 24))
#define WBYTE1(a)					((Byte)((a) >> 16))
#define WBYTE2(a)					((Byte)((a) >> 8))
#define WBYTE3(a)					((Byte)(a))
#define MakeWord(a, b, c, d)		(((Word)(a) << 24) | ((Word)(b) << 16) | ((Word)(c) << 8) | (Word)(d))
#define MAKEWORDS(a, b)				(((Word)(a) << 16) | (Word)(b))
#define REVERSEWORD(a)				(((a) << 24) | ((a) >> 24) | (((a) & 0x0FF00) << 8) | (((a) & 0x0FF0000) >> 8))

// Operations with SHORTs
#define SBYTE0(a)					((Byte)((a) >> 8))
#define SBYTE1(a)					((Byte)(a))
#define MAKESHORT(a, b)				(((Short)(a) << 8) | (Short)(b))

// Bit operations with DWORDs
// Bit 0 is the least significant bit
// Bit 63 is the most significant bit
#define GETBIT(a, b)				(((a) >> (b)) & ONE)
#define SETBIT(a, b)				((a) = (a) | (ONE << (b)))
#define CLRBIT(a, b)				((a) = (a) & (~(ONE << (b))))
#define PUTBIT(a, b, c)				(((c) == 1) ? SETBIT((a), (b)) : CLRBIT((a), (b)))
#define STIRBITS(a, b, c, d)		{ d = 0; for (int ii = 0; ii < (b); ii++) PUTBIT((d), ii, GETBIT((a), (c)[ii])); }
#define MIRROR(a, b, c)				{ c = 0; for (int ii = 0; ii < (b); ii++) { c <<= 1; c |= (a >> ii) & 1; } }

// Bit operations with BYTEs
#define ROT2(a)						(((a) << 2) | (((a) >> 6) & 3))

#endif // __CRYPTO_HPP__
1
Администратор
83610 / 52188 / 244
Регистрация: 10.04.2006
Сообщений: 13,425
31.03.2008, 17:58 10
Способ 2.
Код
		/*  DES Encryption & Decryption Code */

# include <stdio.h>
# include <fstream.h>
# include <string.h>
# include <conio.h>
# include <iostream.h>
	int key[64]={
		0,0,0,1,0,0,1,1,
		0,0,1,1,0,1,0,0,
		0,1,0,1,0,1,1,1,
		0,1,1,1,1,0,0,1,
		1,0,0,1,1,0,1,1,
		1,0,1,1,1,1,0,0,
		1,1,0,1,1,1,1,1,
		1,1,1,1,0,0,0,1
		};
class Des
{
 public:
  int keyi[16][48],
      total[64],
      left[32],
      right[32],
      ck[28],
      dk[28],
      expansion[48],
      z[48],
      xor1[48],
      sub[32],
      p[32],
      xor2[32],
      temp[64],
      pc1[56],
      ip[64],
      inv[8][8];

  char final[1000];
  void IP();
  void PermChoice1();
  void PermChoice2();
  void Expansion();
  void inverse();
  void xor_two();
  void xor_oneE(int);
  void xor_oneD(int);
  void substitution();
  void permutation();
  void keygen();
  char * Encrypt(char *);
  char * Decrypt(char *);
};
void Des::IP() //Initial Permutation
{
	int k=58,i;
	for(i=0;i<32;i++)
	{
	   ip[i]=total[k-1];
	   if(k-8>0)  k=k-8;
	   else       k=k+58;
	}
	k=57;
	for( i=32;i<64;i++)
	{
		ip[i]=total[k-1];
		if(k-8>0)   k=k-8;
		else	    k=k+58;
	}
}
void Des::PermChoice1() //Permutation Choice-1
{
	int k=57,i;
	for(i=0;i<28;i++)
	{
		pc1[i]=key[k-1];
		if(k-8>0)    k=k-8;
		else	     k=k+57;
	}
	k=63;
	for( i=28;i<52;i++)
	{
		pc1[i]=key[k-1];
		if(k-8>0)    k=k-8;
		else         k=k+55;
	}
	k=28;
	for(i=52;i<56;i++)
	{
		pc1[i]=key[k-1];
		k=k-8;
	}

}
void Des::Expansion() //Expansion Function applied on `right' half
{
	int exp[8][6],i,j,k;
	for( i=0;i<8;i++)
	{
		for( j=0;j<6;j++)
		{
			if((j!=0)||(j!=5))
			{
				k=4*i+j;
				exp[i][j]=right[k-1];
			}
			if(j==0)
			{
				k=4*i;
				exp[i][j]=right[k-1];
			}
			if(j==5)
			{
				k=4*i+j;
				exp[i][j]=right[k-1];
			}
		}
	}
	exp[0][0]=right[31];
	exp[7][5]=right[0];

	k=0;
	for(i=0;i<8;i++)
	for(j=0;j<6;j++)
	expansion[k++]=exp[i][j];
}
void Des::PermChoice2()
{
	int per[56],i,k;
	for(i=0;i<28;i++) per[i]=ck[i];
	for(k=0,i=28;i<56;i++) per[i]=dk[k++];

	z[0]=per[13];z[1]=per[16];z[2]=per[10];z[3]=per[23];z[4]=per[0];z[5]=per[4];z[6]=per[2];z[7]=per[27];
	z[8]=per[14];z[9]=per[5];z[10]=per[20];z[11]=per[9];z[12]=per[22];z[13]=per[18];z[14]=per[11];z[15]=per[3];
	z[16]=per[25];z[17]=per[7];z[18]=per[15];z[19]=per[6];z[20]=per[26];z[21]=per[19];z[22]=per[12];z[23]=per[1];
	z[24]=per[40];z[25]=per[51];z[26]=per[30];z[27]=per[36];z[28]=per[46];z[29]=per[54];z[30]=per[29];z[31]=per[39];
	z[32]=per[50];z[33]=per[46];z[34]=per[32];z[35]=per[47];z[36]=per[43];z[37]=per[48];z[38]=per[38];z[39]=per[55];
	z[40]=per[33];z[41]=per[52];z[42]=per[45];z[43]=per[41];z[44]=per[49];z[45]=per[35];z[46]=per[28];z[47]=per[31];
}
void Des::xor_oneE(int round) //for Encrypt
{
 int i;
	for(i=0;i<48;i++)
	    xor1[i]=expansion[i]^keyi[round-1][i];
}
void Des::xor_oneD(int round) //for Decrypt
{
 int i;
	for(i=0;i<48;i++)
	    xor1[i]=expansion[i]^keyi[16-round][i];
}

void Des::substitution()
{
	int s1[4][16]={
		14,4,13,1,2,15,11,8,3,10,6,12,5,9,0,7,
		0,15,7,4,14,2,13,1,10,6,12,11,9,5,3,8,
		4,1,14,8,13,6,2,11,15,12,9,7,3,10,5,0,
		15,12,8,2,4,9,1,7,5,11,3,14,10,0,6,13
	  };

	int s2[4][16]={
		15,1,8,14,6,11,3,4,9,7,2,13,12,0,5,10,
		3,13,4,7,15,2,8,14,12,0,1,10,6,9,11,5,
		0,14,7,11,10,4,13,1,5,8,12,6,9,3,2,15,
		13,8,10,1,3,15,4,2,11,6,7,12,0,5,14,9
	   };

	int s3[4][16]={
		10,0,9,14,6,3,15,5,1,13,12,7,11,4,2,8,
		13,7,0,9,3,4,6,10,2,8,5,14,12,11,15,1,
		13,6,4,9,8,15,3,0,11,1,2,12,5,10,14,7,
		1,10,13,0,6,9,8,7,4,15,14,3,11,5,2,12
	   };

	int s4[4][16]={
		7,13,14,3,0,6,9,10,1,2,8,5,11,12,4,15,
		13,8,11,5,6,15,0,3,4,7,2,12,1,10,14,9,
		10,6,9,0,12,11,7,13,15,1,3,14,5,2,8,4,
		3,15,0,6,10,1,13,8,9,4,5,11,12,7,2,14
	   };

	int s5[4][16]={
		2,12,4,1,7,10,11,6,8,5,3,15,13,0,14,9,
		14,11,2,12,4,7,13,1,5,0,15,10,3,9,8,6,
		4,2,1,11,10,13,7,8,15,9,12,5,6,3,0,14,
		11,8,12,7,1,14,2,13,6,15,0,9,10,4,5,3
	   };

	int s6[4][16]={
		12,1,10,15,9,2,6,8,0,13,3,4,14,7,5,11,
		10,15,4,2,7,12,9,5,6,1,13,14,0,11,3,8,
		9,14,15,5,2,8,12,3,7,0,4,10,1,13,11,6,
		4,3,2,12,9,5,15,10,11,14,1,7,6,0,8,13
	   };

	int s7[4][16]={
		4,11,2,14,15,0,8,13,3,12,9,7,5,10,6,1,
		13,0,11,7,4,9,1,10,14,3,5,12,2,15,8,6,
		1,4,11,13,12,3,7,14,10,15,6,8,0,5,9,2,
		6,11,13,8,1,4,10,7,9,5,0,15,14,2,3,12
	   };

	int s8[4][16]={
		13,2,8,4,6,15,11,1,10,9,3,14,5,0,12,7,
		1,15,13,8,10,3,7,4,12,5,6,11,0,14,9,2,
		7,11,4,1,9,12,14,2,0,6,10,13,15,3,5,8,
		2,1,14,7,4,10,8,13,15,12,9,0,3,5,6,11
	   };
	int a[8][6],k=0,i,j,p,q,count=0,g=0,v;

	for(i=0;i<8;i++)
	{
		for(j=0;j<6;j++)
		{
			a[i][j]=xor1[k++];
		}
	}

	for( i=0;i<8;i++)
	{
		p=1;q=0;
		k=(a[i][0]*2)+(a[i][5]*1);
		j=4;
		while(j>0)
		{
			q=q+(a[i][j]*p);
			p=p*2;
			j--;
		}
		count=i+1;
		switch(count)
		{
		case 1:	v=s1[k][q];	break;
		case 2:	v=s2[k][q];	break;
		case 3:	v=s3[k][q];	break;
		case 4:	v=s4[k][q];	break;
		case 5:	v=s5[k][q];	break;
		case 6:	v=s6[k][q];	break;
		case 7:	v=s7[k][q];	break;
		case 8:	v=s8[k][q];	break;
		}

		int d,i=3,a[4];
		while(v>0)
		{
			d=v%2;
			a[i--]=d;
			v=v/2;
		}
		while(i>=0)
		{
			a[i--]=0;
		}

		for(i=0;i<4;i++)
		sub[g++]=a[i];
	}
}

void Des::permutation()
{
	p[0]=sub[15];p[1]=sub[6];p[2]=sub[19];p[3]=sub[20];p[4]=sub[28];p[5]=sub[11];p[6]=sub[27];p[7]=sub[16];
	p[8]=sub[0];p[9]=sub[14];p[10]=sub[22];p[11]=sub[25];p[12]=sub[4];p[13]=sub[17];p[14]=sub[30];p[15]=sub[9];
	p[16]=sub[1];p[17]=sub[7];p[18]=sub[23];p[19]=sub[13];p[20]=sub[31];p[21]=sub[26];p[22]=sub[2];p[23]=sub[8];
	p[24]=sub[18];p[25]=sub[12];p[26]=sub[29];p[27]=sub[5];p[28]=sub[21];p[29]=sub[10];p[30]=sub[3];p[31]=sub[24];
}

void Des::xor_two()
{
 int i;
	for(i=0;i<32;i++)
	{
		xor2[i]=left[i]^p[i];
	}
}

void Des::inverse()
{
	int p=40,q=8,k1,k2,i,j;
	for(i=0;i<8;i++)
	{
		k1=p;k2=q;
		for(j=0;j<8;j++)
		{
			if(j%2==0)
			{
				inv[i][j]=temp[k1-1];
				k1=k1+8;
			}
			else if(j%2!=0)
			{
				inv[i][j]=temp[k2-1];
				k2=k2+8;
			}
		}
		p=p-1;q=q-1;
	}
}

char * Des::Encrypt(char *Text1)
{
  int i,a1,j,nB,m,iB,k,K,B[8],n,t,d,round;
  char *Text=new char[1000];
  strcpy(Text,Text1);
  i=strlen(Text);
  int mc=0;
  a1=i%8;
 if(a1!=0) for(j=0;j<8-a1;j++,i++) Text[i]=' '; Text[i]='\0';
 keygen();
  for(iB=0,nB=0,m=0;m<(strlen(Text)/8);m++) //Repeat for TextLenth/8 times.
  {
     for(iB=0,i=0;i<8;i++,nB++)
      {
		 n=(int)Text[nB];
		 for(K=7;n>=1;K--)
		 {
		  B[K]=n%2;  //Converting 8-Bytes to 64-bit Binary Format
		  n/=2;
		 } for(;K>=0;K--) B[K]=0;
	   for(K=0;K<8;K++,iB++) total[iB]=B[K]; //Now `total' contains the 64-Bit binary format of 8-Bytes
      }
	IP(); //Performing initial permutation on `total[64]'
	for(i=0;i<64;i++) total[i]=ip[i]; //Store values of ip[64] into total[64]

	for(i=0;i<32;i++) left[i]=total[i]; // 		  +--> left[32]
					    // total[64]--|
	for(;i<64;i++) right[i-32]=total[i];//            +--> right[32]
    for(round=1;round<=16;round++)
    {
	Expansion(); //Performing expansion on `right[32]' to get  `expansion[48]'
	xor_oneE(round); //Performing XOR operation on expansion[48],z[48] to get xor1[48]
	substitution();//Perform substitution on xor1[48] to get sub[32]
	permutation(); //Performing Permutation on sub[32] to get p[32]
	xor_two(); //Performing XOR operation on left[32],p[32] to get xor2[32]
	for(i=0;i<32;i++) left[i]=right[i]; //Dumping right[32] into left[32]
	for(i=0;i<32;i++) right[i]=xor2[i]; //Dumping xor2[32] into right[32]
     }
	for(i=0;i<32;i++) temp[i]=right[i]; // Dumping   -->[ swap32bit ]
	for(;i<64;i++) temp[i]=left[i-32];  //    left[32],right[32] into temp[64]

	inverse(); //Inversing the bits of temp[64] to get inv[8][8]
	/* Obtaining the Cypher-Text into final[1000]*/
		   k=128;   d=0;
		for(i=0;i<8;i++)
		{
		  for(j=0;j<8;j++)
		  {
		    d=d+inv[i][j]*k;
		    k=k/2;
		  }
		   final[mc++]=(char)d;
		   k=128;   d=0;
		}
  } //for loop ends here
  final[mc]='\0';
  return(final);
}
char * Des::Decrypt(char *Text1)
{
  int i,a1,j,nB,m,iB,k,K,B[8],n,t,d,round;
  char *Text=new char[1000];
  unsigned char ch;
  strcpy(Text,Text1);
  i=strlen(Text);
keygen();
int mc=0;
  for(iB=0,nB=0,m=0;m<(strlen(Text)/8);m++) //Repeat for TextLenth/8 times.
  {
     for(iB=0,i=0;i<8;i++,nB++)
      {
		 ch=Text[nB];
		 n=(int)ch;//(int)Text[nB];
		 for(K=7;n>=1;K--)
		 {
		  B[K]=n%2;  //Converting 8-Bytes to 64-bit Binary Format
		  n/=2;
		 } for(;K>=0;K--) B[K]=0;
	   for(K=0;K<8;K++,iB++) total[iB]=B[K]; //Now `total' contains the 64-Bit binary format of 8-Bytes
      }
	IP(); //Performing initial permutation on `total[64]'
	for(i=0;i<64;i++) total[i]=ip[i]; //Store values of ip[64] into total[64]

	for(i=0;i<32;i++) left[i]=total[i]; // 		  +--> left[32]
					    // total[64]--|
	for(;i<64;i++) right[i-32]=total[i];//            +--> right[32]
      for(round=1;round<=16;round++)
      {
	Expansion(); //Performing expansion on `right[32]' to get  `expansion[48]'
	xor_oneD(round);
	substitution();//Perform substitution on xor1[48] to get sub[32]
	permutation(); //Performing Permutation on sub[32] to get p[32]
	xor_two(); //Performing XOR operation on left[32],p[32] to get xor2[32]
	for(i=0;i<32;i++) left[i]=right[i]; //Dumping right[32] into left[32]
	for(i=0;i<32;i++) right[i]=xor2[i]; //Dumping xor2[32] into right[32]
     } //rounds end here
	for(i=0;i<32;i++) temp[i]=right[i]; // Dumping   -->[ swap32bit ]
	for(;i<64;i++) temp[i]=left[i-32];  //    left[32],right[32] into temp[64]

	inverse(); //Inversing the bits of temp[64] to get inv[8][8]
	/* Obtaining the Cypher-Text into final[1000]*/
		   k=128;   d=0;
		for(i=0;i<8;i++)
		{
		  for(j=0;j<8;j++)
		  {
		    d=d+inv[i][j]*k;
		    k=k/2;
		  }
		   final[mc++]=(char)d;
		   k=128;   d=0;
		}
  } //for loop ends here
  final[mc]='\0';
  char *final1=new char[1000];
  for(i=0,j=strlen(Text);i<strlen(Text);i++,j++)
    final1[i]=final[j]; final1[i]='\0';
  return(final);
}
void main()
{
 Des d1,d2;
 char *str=new char[1000];
 char *str1=new char[1000];
 clrscr();
 //strcpy(str,"PHOENIX it & ece solutions.");
 cout<<"Enter a string : ";
  gets(str);
 str1=d1.Encrypt(str);
 cout<<"\ni/p Text: "<<str<<endl;
 cout<<"\nCypher  : "<<str1<<endl;
//	 ofstream fout("out2_fil.txt"); fout<<str1; fout.close();
 cout<<"\no/p Text: "<<d2.Decrypt(str1)<<endl;
 getch();
}

void Des::keygen()
{
	PermChoice1();

	int i,j,k=0;
	for(i=0;i<28;i++)
	{
		ck[i]=pc1[i];
	}
	for(i=28;i<56;i++)
	{
		dk[k]=pc1[i];
		k++;
	}
	int noshift=0,round;
	for(round=1;round<=16;round++)
	{
		if(round==1||round==2||round==9||round==16)
			noshift=1;
		else
			noshift=2;
		while(noshift>0)
		{
			int t;
			t=ck[0];
			for(i=0;i<28;i++)
			ck[i]=ck[i+1];
			ck[27]=t;
			t=dk[0];
			for(i=0;i<28;i++)
			dk[i]=dk[i+1];
			dk[27]=t;
			noshift--;
		}
		PermChoice2();
		for(i=0;i<48;i++)
			keyi[round-1][i]=z[i];
	}
}
1
0 / 0 / 1
Регистрация: 27.03.2008
Сообщений: 75
31.03.2008, 18:10  [ТС] 11
Спасибо!!!
Но во втором варианте у меня ошибку выдает здесь:

C++
1
2
3
4
5
6
Des d1,d2;
 char *str=new char[1000];
 char *str1=new char[1000];
 //!!!!!clrscr();!!!!!!
 //strcpy(str,"PHOENIX it & ece solutions.");
 cout<<"Enter a string : ";
F:\Program Files\Microsoft Visual Studio\MyProjects\proba\1.cpp(424) : error C2065: 'clrscr' : undeclared identifier
0
0 / 0 / 1
Регистрация: 27.03.2008
Сообщений: 75
31.03.2008, 18:16  [ТС] 12
а первый вариант выдает ошибку -
Linking...
LIBCD.lib(crt0.obj) : error LNK2001: unresolved external symbol _main
Debug/proba2.exe : fatal error LNK1120: 1 unresolved externals
Error executing link.exe.
0
Администратор
83610 / 52188 / 244
Регистрация: 10.04.2006
Сообщений: 13,425
31.03.2008, 18:34 13
Цитата Сообщение от Splendid
error C2065: 'clrscr' : undeclared identifier
clrscr - это нестандартная функция. Ее можно реализовать например так:
Код
void clear_screen()
{
    for(int i = 0; i < 50; i++) 
        cout<<endl;
}
Цитата Сообщение от Splendid
а первый вариант выдает ошибку -
Linking...
LIBCD.lib(crt0.obj) : error LNK2001: unresolved external symbol _main
Debug/proba2.exe : fatal error LNK1120: 1 unresolved externals
Error executing link.exe.
Потому что это не программа, а вспомогательный класс, там нет функции main()
0
0 / 0 / 1
Регистрация: 27.03.2008
Сообщений: 75
01.04.2008, 09:57  [ТС] 14
mik-a-el, а вот во втором варианте - я добавила
C++
1
2
3
4
5
void clrscr()
{
    for(int i = 0; i < 50; i++) 
        cout<<endl;
}
в начало программы, код скомпилился - все ок.
Но когда запускаешь - выводится пустое окно - набираешь что-нибудь, например 123 и выводится -
Enter a string:
i/p Text: 123
Cypher: ну тут шифрованный текст
o/p Text: 123

Вопрос вот в чем - а почему не нужно вводить ключ шифрования???
0
Администратор
83610 / 52188 / 244
Регистрация: 10.04.2006
Сообщений: 13,425
01.04.2008, 10:24 15
Там есть какая-то переменная key - это не оно?
0
0 / 0 / 1
Регистрация: 27.03.2008
Сообщений: 75
01.04.2008, 10:35  [ТС] 16
может и оно Но как ее в майн присобачить? Т.е. как сделать так, чтобы пользователь должен был ввести - ключ и текст, а ему бы выдало шифр?
Простите за дурацкие вопросы - но я ни на си ни на си ++ не писала никогда...
0
0 / 0 / 1
Регистрация: 27.03.2008
Сообщений: 75
01.04.2008, 10:38  [ТС] 17
и еще такой вопрос - этот код на С++ (я так поняла, по крайней мере) - его вообще реально "подправить", чтобы он стал на С?
0
Администратор
83610 / 52188 / 244
Регистрация: 10.04.2006
Сообщений: 13,425
01.04.2008, 11:02 18
Цитата Сообщение от Splendid
Но как ее в майн присобачить? Т.е. как сделать так, чтобы пользователь должен был ввести - ключ и текст, а ему бы выдало шифр?
Я думаю, что в этом уже вам нужно разобраться
Цитата Сообщение от Splendid
этот код на С++ (я так поняла, по крайней мере) - его вообще реально "подправить", чтобы он стал на С?
Да.
0
0 / 0 / 1
Регистрация: 27.03.2008
Сообщений: 75
01.04.2008, 11:25  [ТС] 19
а подскажите хотябы, что править надо, в какую сторону вообще смотреть?
0
01.04.2008, 11:25
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
01.04.2008, 11:25
Помогаю со студенческими работами здесь

Метод простых итераций. Не могу преобразовать функцию и нормально разобраться с реализацией
Не понимаю, как преобразовать функции, раз 50 уже прочёл, вроде понял, реализовать на с++ вроде бы...

Помогите с выбором и реализацией редиректа
Здравствуйте! На сервер myserver.com происходит переход вот по такой ссылке: ...

помогите с реализацией алгоритма сжатия Хаффмана
помогите с реализацией алгоритма сжатия Хаффмана есть код в с++ в консольном приложении,...

Помогите с реализацией поиска в формах MS Access!!!
Ребят, нужна сторонняя помощь по поиску в форме MS Access. Сам я плохо владею VB - работаю с...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
19
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru