Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download
Views: 549
1
#include "des56.h"
2
3
#include <stdlib.h>
4
#include <stdio.h>
5
#include <string.h>
6
7
//Use these constants to specify ENCRYPT or DECRYPT in the fencrypt function call. (The middle parameter)
8
#define ENCRYPT 0
9
#define DECRYPT 1
10
11
/*This function takes the XOR of block A and block B and stores the result in block "result"*/
12
/*Note that it is possible that "result" is the same as "A" (or "B").*/
13
/*For example:
14
XORblock(block1,IV,block1);
15
Would XOR the first block with the IV and put the result in block1*/
16
void XORblock(char A[8], char B[8], char result[8])
17
{
18
int i = 0;
19
for(;i<8;i++)
20
result[i] = A[i]^B[i];
21
}
22
23
/*This function takes a block as input and prints the corresponding hex to the terminal*/
24
void printhex(unsigned char block[8])
25
{
26
int i=0;
27
for(;i<8;i++)
28
printf(" 0x%x ",block[i]);
29
puts("");
30
}
31
32
void cbc_enc_three_blocks(char block1[8], char block2[8], char block3[8], char IV[8],keysched *ks)
33
{
34
XORblock(block1, IV, block1);
35
fencrypt(block1, 0, ks);
36
XORblock(block2, block1, block2);
37
fencrypt(block2, 0, ks);
38
XORblock(block3, block2, block3);
39
fencrypt(block3, 0, ks);
40
}
41
42
void cbc_dec_three_blocks(char block1[8], char block2[8], char block3[8], char IV[8],keysched *ks)
43
{
44
char temp1[8];
45
char temp2[8];
46
char temp3[8];
47
48
for(int i = 0; i < 8; i++)
49
{
50
temp1[i] = block1[i];
51
temp2[i] = block2[i];
52
temp3[i] = block3[i];
53
}
54
55
fencrypt(block1,1,ks);
56
XORblock(block1, IV, block1);
57
fencrypt(block2,1,ks);
58
XORblock(block2, temp1, block2);
59
fencrypt(block3,1,ks);
60
XORblock(block3, temp2, block3);
61
}
62
63
int main()
64
{
65
unsigned char key[8] = {1,2,3,4,5,6,7,8}; //This will be the key
66
keysched *ks = malloc(sizeof(keysched)); //Initialize the key schedule data structure
67
fsetkey(key,ks); //Build the key schedule
68
unsigned char* all_blocks = malloc(3*8*sizeof(char)); //24 bytes of memory, representing 3 DES blocks
69
bzero(all_blocks,8*3); //Initialize the blocks to all 0s
70
71
all_blocks[0] = 'A'; //Put 0x41=='A' into the first byte of the first block
72
73
/*The file "plaintext.txt", created below, will be useful for testing.*/
74
FILE* pt_f = fopen("plaintext.txt","wb");
75
fwrite(all_blocks,8,3,pt_f); //write 3 blocks, each of length 8 bytes
76
fclose(pt_f);
77
78
unsigned char IV[8] = {0}; //The IV will be all zeros
79
80
cbc_enc_three_blocks(all_blocks,all_blocks+8,all_blocks+16,IV,ks); //Do the encryption
81
FILE* fp = fopen("encryption.des","wb"); //Save the result
82
fwrite(all_blocks,8,3,fp); //write 3 blocks, each of length 8 bytes
83
fclose(fp);
84
85
cbc_dec_three_blocks(all_blocks,all_blocks+8,all_blocks+16,IV,ks); //Do the decryption
86
fp = fopen("decryption.txt","wb"); //Save the result
87
fwrite(all_blocks,8,3,fp); //write 3 blocks, each of length 8 bytes
88
fclose(fp);
89
}
90