# C Cryptography Assignment need help

This topic is 3490 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I recently got a programming assignment that I am unable to complete. Basically there are three messages that have been incrypted, and we need to desipher all of them, we were given instructions on the first one, and once that was solved it contains instructions on how to complete the next one and so forth. I maganed to get the first one done but now I'm stuck. We can only edit the crypt.c file as well. here are the source files Crypt.c
#include "crypt.h"

/*
* An encrypting function - all encrypting and decrypting functions follow
* this template:
*    inbuffer :: 		the input message
*    outbuffer ::		the output encoded/decoded message
*    key ::			a generic pointer to an object that is the encoding key
*
* This function is used to encrypt a message using Caesar's shift algorithm.
*/
void caesar(buffer_t *inmessage, buffer_t *outmessage, void *key)
{
long i;
int offset = *((uint8_t*)key) - 'a';

for(i=0; i &lt; inmessage-&gt;length; i++)
{
outmessage-&gt;buffer[i] = (inmessage-&gt;buffer[i] + offset) % ASCII_TABLE_SIZE;
}
}

/*
* Start here - replace me with a useful comment
*/
void decaesar(buffer_t *inmessage, buffer_t *outmessage, void *key)
{
long i;
int offset = *((uint8_t*)key) - 'a';

for(i=0; i &lt; inmessage-&gt;length; i++)
{
outmessage-&gt;buffer[i] = (inmessage-&gt;buffer[i] - offset) % ASCII_TABLE_SIZE;
}
}

/*
* A function to find the encoding/decoding function from a command-line text string
*/
encoder_function_t get_encoder(char* encoder_name)
{
if (strcmp(encoder_name, "caesar") == 0)
{
return caesar;
}

if (strcmp(encoder_name, "decaesar") == 0)
{
return decaesar;
}

exit(1);
return NULL;
}


Crypt.h
#ifndef CRYPT_H_
#define CRYPT_H_

#include&lt;stdio.h&gt;
#include&lt;stdlib.h&gt;
#include&lt;stdint.h&gt;
#include&lt;string.h&gt;

/*
* Define a memory structure for handling message objects
*   _length :: 		length of the message
*   _buffer_size ::	size of the memory (buffer) _length &lt; _buffer_szie
*   _buffer ::			message array data is here
*/
typedef struct {
long length;
long buffer_size;
uint8_t *buffer;
} buffer_t;

/*
* Define a union of key types
*/
typedef union {
char charkey;
long hexkey;
} key_tt;
enum {CHARKEY, HEXKEY};

/*
* Define a structure for holding the command line parameters
*/
typedef struct {
char* methodname;
char* input;
char* output;
int   keytype;
key_tt key;
} cl_parameters;

/*
* Define a type that is a function pointer
*    function returns void
*    function parameters are
*       buffer_t *input_message
*       buffer_t *output_message
*       void *key_object
*
* If you understand this bit of code and can use it, then you are a very able programmer -
* have a chat to the TAs and lecturers, we're always keen to identify people in this category
*/
typedef void (*encoder_function_t)(buffer_t*, buffer_t*, void*);

/*
* Define some constants for a reduced 6-bit ASCII table
*/
#define ASCII_PRINTABLE_START ' '
#define ASCII_PRINTABLE_STOP  '^'
#define ASCII_PRINTABLE_TABLE_SIZE ((ASCII_PRINTABLE_STOP - ASCII_PRINTABLE_START + 2))
#define ASCII_TABLE_SIZE 256

/*
* Define function prototypes in main.c
*/
buffer_t* new_buffer(long length);
void delete_buffer(buffer_t *buffer);
long filesize(char filename[]);
buffer_t* read_message(char filename[], buffer_t *outbuffer);
void write_message(char filename[], buffer_t *inbuffer);
cl_parameters parse_cl(int argc, char *argv[]);

/*
* Define function prototypes in crypt.c
*/
encoder_function_t get_encoder(char* encoder_name);

#endif /*CRYPT_H_*/


main.c
#include "crypt.h"

/*
* A function to create a message buffer object - takes a length measure as a indictation
* of how big a message buffer is required.  The actually object will be bigger by 4/3 (approx)
*/
buffer_t* new_buffer(long length)
{
buffer_t *buffer;
long buffer_size;

buffer_size = (length/3 + 1) * 4;
buffer = (buffer_t*)malloc(sizeof(buffer_t));
if (buffer == NULL)
{
printf("Error allocating buffer object, out of memory\n");
exit(1);
}
buffer-&gt;buffer = (uint8_t*)calloc(buffer_size, sizeof(uint8_t));
if (buffer-&gt;buffer == NULL)
{
printf("Error allocating buffer, out of memory\n");
exit(1);
}
buffer-&gt;buffer_size = buffer_size;
buffer-&gt;length = length;

return(buffer);
}

/*
* A function to delete the buffer object.
*/
void delete_buffer(buffer_t *buffer)
{
free(buffer-&gt;buffer);
free(buffer);
}

/*
* A function that computes the size of a file (message).
* This function is used to find the size of the message so that a message buffer object of the
* right size can be created.
*/
long filesize(char filename[])
{
FILE *fhandler;
long size;

fhandler = fopen(filename, "rb");
if (fhandler == NULL)
{
printf("Can't open file (%s) for reading\n", filename);
exit(1);
}

fseek(fhandler, 0, SEEK_END);
size =  ftell(fhandler);

fclose(fhandler);

return size;
}

/*
* A function to read a file and put its contents in the message buffer "outbuffer"
*/
buffer_t* read_message(char filename[], buffer_t *outbuffer)
{
FILE *fhandler;

fhandler = fopen(filename, "rb");
if (fhandler == NULL)
{
printf("Can't open file (%s) for reading\n", filename);
exit(1);
}

if (outbuffer-&gt;length != fread(outbuffer-&gt;buffer, sizeof(uint8_t), outbuffer-&gt;length, fhandler))
{
printf("Error reading file (%s)\n", filename);
exit(1);
}

fclose(fhandler);

return outbuffer;
}

/*
* A function that creates (or recreates) a new file with name "filename" and writes the contents of
* "inbuffer" to the file
*/
void write_message(char filename[], buffer_t *inbuffer)
{
FILE *fhandler;

if (strcmp(filename, "-") == 0)
{
printf("%s\n", inbuffer-&gt;buffer);
}
else
{
fhandler = fopen(filename, "wb");
if (fhandler == NULL)
{
printf("Can't open file (%s) for writing\n", filename);
exit(1);
}

if (inbuffer-&gt;length != fwrite(inbuffer-&gt;buffer, sizeof(uint8_t), inbuffer-&gt;length, fhandler))
{
printf("Error writing file (%s)\n", filename);
exit(1);
}

fclose(fhandler);
}
}

/*
* A function to parse the command line to find the
*    crypt_method
*    optional key
*    input message filename
*    output message filename
*/
cl_parameters parse_cl(int argc, char *argv[])
{
int i,j,k;

cl_parameters parameters;
if (!(argc == 4 || argc == 6))
{
printf("\n\nError in call to crypt function\n\n");
printf("Correct usage is:\n");
printf("\tcrypt crypt_method [key] input_message_filename output_message_filename\n\n");
printf("The optional key is one of the form:\n");
printf("\t--charkey character\n");
printf("\t--hexkey hex_long_value\n");
exit(1);
}

for(i=1; i &lt; argc; i++)
{
if (strcmp(argv[i], "--charkey") == 0)
{
parameters.keytype = CHARKEY;
parameters.key.charkey = argv[i+1][0];
for (j=i+2, k=i;   j &lt; argc;   j++, k++)
{
argv[k] = argv[j];
}
argc = argc-2;
break;
}
if (strcmp(argv[i], "--hexkey") == 0)
{
parameters.keytype = HEXKEY;
sscanf(argv[i+1], "%lx", &(parameters.key.hexkey));
for (j=i+2, k=i;   j &lt; argc;   j++, k++)
{
argv[k] = argv[j];
}
argc = argc-2;
break;
}
}

parameters.methodname = argv[1];
parameters.input = argv[2];
parameters.output = argv[3];

return parameters;
}
/*
* Main function::
*    1. Parse the command-line
*    2. Create the message buffers
*    3. Read the input file message
*    4. Call the encoder/decoder method
*    5. Write encoded/decoded message to the output file
*
* Usage::
*    crypt method [key] input_message-file output_message_file
*
* Key::
*    The key is optional, and takes two forms
*    --charkey char
*    --hexkey  hex_long_value
*/
int main(int argc, char *argv[])
{
long message_size;
buffer_t *inmessage;
buffer_t *outmessage;
cl_parameters parameters;
encoder_function_t method;

parameters = parse_cl(argc, argv);
method = get_encoder(parameters.methodname);

message_size = filesize(parameters.input);
inmessage = new_buffer(message_size);
outmessage = new_buffer(message_size);

(*method)(inmessage, outmessage, (void*)&(parameters.key));
write_message(parameters.output, outmessage);

return 0;
}

message1
Gsrkvexypexmsrw%Xli$vi{evh$jsv$wyggiww$mw22222$qsvi${svo282$Fmx1wlmjxmrk$irgshivXli$wigsrh$qiwweki$mw$irgv}txih$ywmrk$e$wgliqi$xlex$M$lezi$gsqi$yt${mxl2$$Mxmwvipexmzip}wmqtpixsfvieo0fyxxlivimwrsriihewM{mppi|tpemrmxfips{2$$Xli$viep$tyvtswi$filmrh$xlmw$irgshiv$erh$higshiv$mw$xs$hizipst$wsqi$fmx$qermtypexmsr$womppw2EWGMM$mw$e$;1fmx$gshi0${lmgl$tivqmxw$yw$xs$ywi$xli$qswx$wmkrmjmgerx$fmx$,;xl$fmx${lir$gsyrxmrk$jvsq$4-$jsv$sxliv$tyvtswiw$1$tvszmhi${i$hmwgevh$mx$pexxiv2$Ywmrk$xlmw$ors{pihki$M$lezi$hizmwih$xli$jspps{mrk$wgliqi$jsv$irgshmrk$e$glevegxiv>
52$Gsqtyxi$xli$shh1tevmx}$sj$xli$glevegxiv$,5$mj$xlivi$evi$er$shh$ryqfiv$sj$5+w$mr$xli$;1fmx$EWGMM$gshi0$sxliv{mwi$4-
62$Wix$xli$;xl1fmx$xs$fi$xli$gsqtyxih$shh1tevmx}$,jvsq$wxit$5- 72$W{et$xli$;xl$erh$8xl$fmxw$111$figeywi${i$ger$erh$xlmw${mpp$qeoi$xlmrkw$qsvi$mrxiviwxmrk
82$Mj$xli$EWGMM1gshi$lew$shh$tevmx}$xlir$\SV$xli$8$piewx$wmkrmjmgerx$fmxw${mxl$er$<1fmx$li|$zepyi$tewwih$mr$ew$e$oi}$xs$xli$epksvmxlq2
Xs$emh$mr${vmxmrk$}syv$higshiv$jyrgxmsr$}sy$qywx$epws${vmxi$e$wix$sj$ewwmwxmrk$jyrgxmsrw$sv$ew$QEGVSW2$$Mxmwqsvigsrzirxmsrepxs{vmxixliqewQEGVSW0fyx}sygerqeoixliglsmgi2$$Iegl$qywx$tvszmhi$xli$jyrgxmsrepmx}$ew$hiwgvmfih$fips{> 52$FZ,|-$>>$vixyvr$er$yrwmkrih$ryqfiv${livi$xli$fmx$ex$tswmxmsr$+|+$mw$wix$5$erh$epp$xli$sxlivw$evi$gpievih$,4-2 62$GPIEVFMX,e0|-$>>$vixyvr$er$yrwmkrih$ryqfiv$iuyep$xs$xli$yrwmkrih$ryqfiv$+e+$i|gitx$xli$fmx$ex$tswmxmsr$+|+$mw$gpiev$sv$42 72$WIXFMX,e0|-$>>$vixyvr$er$yrwmkrih$ryqfiv$iuyep$xs$xli$yrwmkrih$ryqfiv$+e+$i|gitx$xli$fmx$ex$tswmxmsr$+|+$mw$wix$sv$52 82$EWWMKRFMX,e0|0z-$>>$vixyvr$er$yrwmkrih$ryqfiv$iuyep$xs$xli$yrwmkrih$ryqfiv$+e+$i|gitx$xli$fmx$ex$tswmxmsr$+|+$mw$ewwmkrih$xli$zepyi$sj$+z+0${livi$+z+$mw$imxliv$5$sv$42
92$MWGPIEV,e0|-$>>$vixyvr$5$mj$xli$fmx$ex$tswmxmsr$+|+$mr$xli$yrwmkrih$zepyi$+e+$mw$gpiev$sv$40$$sxliv{mwivixyvr42 :2MWWIX,e0|->>vixyvr5mjxlifmxextswmxmsr+|+mrxliyrwmkrihzepyi+e+mwwixsv50sxliv{mwivixyvr42 ]syvhigshmrkjyrgxmsrwlsyphywiexpiewx7sjxlifmxqermtypexmsrqixlshwjvsqefszi2$$Xli$oi}$riihih$xs$higshi$qiwweki$6$mw$4|4E2  message 2 ¥.0Àqc{i~w0e~coteâ Ôxe0äxiât0}eóóqwe0ió0e~câùðäet0õói~w0q0ðqc{i~w0ócxe}e.00Heâe0çe0qâe0woi~w0äo0õóe0q0âetõcet0óõróeä0of0äxe0AÃSYY0äqrle0of0cxqâqcäeâ0coteóª Òetõcet0Sote AÃSYY0Sote Sxqâqcäeâ (teci}ql9 (teci}ql9 ---------------------------------------------------------------------- £² ÛóðqceÝ ± ££ ! ² £´ " £ £¥ 3 ´ £¦$
¥				£·				5
...
¦£				± 				'Ì~'

Meóóqweó0e~cotet0i~0äxió0ócxe}e0co~äqi~0o~lù0o~e0óðeciql0cxqâqcäeâ0---0äxe0\i~e0Veet<0\V0oâ0'Ì~'0---0q0feç0ðõ~cäõqäio~0cxqâqcäeâó0q~t0o~lù0äxe0õððeâcqóe0cxqâqcäeâó0of0äxe0qlðxqreä.00Mq~ù0eqâlù0co}ðõäeâó0çeâe0of0äxió0foâ}0q~t0iä0ió0foâ0äxió0âeqóo~0äxqä0q0loä0of0co}ðõäeâ0óùóäe}ó0qâe0cqóe-i~óe~óiäiöe.

Ôxió0âetõcet0óeä0of0cxqâqcäeâó0xqó0o~lù0¦´0}e}reâó<0q~t0äxeâefoâe0äxeù0cq~0re0õ~iáõelù0ite~äifiet0õói~w0q0¦-riä0cote.00Hoçeöeâ<0äxe0}i~i}õ}0rqóe0óiúe0of0q0óeáõe~ce0(çoât0le~wäx90ió0¸0riäó.00Ôxeâefoâe0i~0£0çoâtó0(²´riäó90çe0cq~0e~cote0´0¦-riä0âetõcet0cote0cxqâqcäeâó.

Meóóqwe0£0ió0e~cotet0i~0äxió0foâ}.00×âiäe0q0tecoteâ0qó0i~0äxe0ðâeöioõó0äço0cqóeó0äo0âeöeql0äxe0xitte~0}eóóqwe.


I wont bother putting message 3 here. I translated message 1 into this:
Congratulations!

The reward for success is..... more work.

4. Bit-shifting encoder
The second message is encrypted using a scheme that I have come up with.  It is relatively simple to break, but there is no need as I will explain it below.  The real purpose behind this encoder and decoder is to develop some bit manipulation skills.

ASCII is a 7-bit code, which permits us to use the most significant bit (7th bit when counting from 0) for other purposes - provide we discard it latter. Using this knowledge I have devised the following scheme for encoding a character:
1. Compute the odd-parity of the character (1 if there are an odd number of 1's in the 7-bit ASCII code, otherwise 0)
2. Set the 7th-bit to be the computed odd-parity (from step 1)
3. Swap the 7th and 4th bits --- because we can and this will make things more interesting
4. If the ASCII-code has odd parity then XOR the 4 least significant bits with an 8-bit hex value passed in as a key to the algorithm.

To aid in writing your decoder function you must also write a set of assisting functions or as MACROS.  It is more conventional to write them as MACROS, but you can make the choice.  Each must provide the functionality as described below:
1. BV(x) :: return an unsigned number where the bit at position 'x' is set 1 and all the others are cleared (0).
2. CLEARBIT(a,x) :: return an unsigned number equal to the unsigned number 'a' except the bit at position 'x' is clear or 0.
3. SETBIT(a,x) :: return an unsigned number equal to the unsigned number 'a' except the bit at position 'x' is set or 1.
4. ASSIGNBIT(a,x,v) :: return an unsigned number equal to the unsigned number 'a' except the bit at position 'x' is assigned the value of 'v', where 'v' is either 1 or 0.
5. ISCLEAR(a,x) :: return 1 if the bit at position 'x' in the unsigned value 'a' is clear or 0,  otherwise return 0.
6. ISSET(a,x) :: return 1 if the bit at position 'x' in the unsigned value 'a' is set or 1, otherwise return 0.

Your decoding function should use at least 3 of the bit manipulation methods from above.  The key needed to decode message 2 is 0x0A.

but i cant understand these instructions to create the function required to decode message 2. Please help me.

##### Share on other sites
I suggest that you take an example character, apply the encoding steps to it and see what you get. Then think about what you need to do to turn the result back into the original character.

If this doesn't help you, you'll need to ask a more specific question.

##### Share on other sites
Which part do you have trouble with... the encoding explanation or the bit-manipulation macros?

BTW, message 2 is not very difficult to decode... I mean, I can read it just by looking at it. Due to the silly parity even/odd scheme and single bit swap, about a quarter of the encoded characters are IDENTICAL to the originals.

##### Share on other sites
the parity is really confusing me, I just need to decode message 2

##### Share on other sites
Well it's just like it says - count the number of bits that are 1 (not counting the MSB), and if the count is odd, the odd-parity is 1, otherwise it's 0.

For example, the odd-parity of 00010110 is 1, but the odd-parity of 10101011 is 0 (again, the MSB doesn't count).

At least that's how I understand it. I've never heard this term before.

##### Share on other sites
http://en.wikipedia.org/wiki/Parity_bit

i know what i have to do but i dont know how to program it with c, we are supposed to edit crypt.c to do this, the one that is currently listed will work out message1, that was simple enough, but im not good enough at c to program it into a function :$#### Share this post ##### Link to post ##### Share on other sites Quote:  Original post by Googol PL3Xim not good enough at c to program it into a function :$

Again, you need to ask a more specific question.

##### Share on other sites
Quote:
Original post by Gage64
Quote:
 Original post by Googol PL3Xim not good enough at c to program it into a function :\$

Again, you need to ask a more specific question.
Indeed, we have a rule here that we don't provide solutions to homework problems. What we can and will do however is help you out with any specific questions you can ask which might lead you towards solving your problem, or help you to troubleshoot errors with an attempted solution.

If the problem is that you're not good enough with C, could you explain what you think you need to do to solve the problem in pseudo-code or as a flowchart? Do you think you could get started on writing a solution, and if so what is it specifically that you're getting stuck on?

##### Share on other sites
I have attempted the solution myself. The key supplied appears to be bogus- no xor encrypting/decrypting is required (but you will probably have to include it for your assignment anyway- and pass a key of 0x00).

As a hint, the first two lines of message 2 reads:
Quote:
 5. Packing EncoderThe third message is encrypted using a packing scheme. Here we are going to use a reduced subset of the ASCII table of character codes:

##### Share on other sites
thank already got it ;)

##### Share on other sites

This topic is 3490 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Create an account or sign in to comment

You need to be a member in order to leave a comment

## Create an account

Sign up for a new account in our community. It's easy!

Register a new account