Domanda

For a school project, I'm writing a blowfish encryption (just the encryption, not the decryption). I've finished the encryption itself, and I decided I would do the decryption for fun (it's easy enough in Blowfish).

I used unsigned chars to represent bytes (although I suppose uint8_t would have been more portable). The question I have comes in when I am attempting to print out the decrypted bytes. I am encrypting plain text messages. I've been able to print out the actual text message that I encrypted, but only at a very specific spot. The same exact code seems not to work anywhere else. Here it is:

int n;
for(n = 0; n < numBlocks; n++) // Blocks are 32-bit unsigned ints (unsigned long)
{
     // uchar is just a typedef for unsigned char
     // message is an array of uchars
     message[n] = (uchar) ((blocks[n]>>24));
     message[n+1] = (uchar) ((blocks[n]>>16));
     message[n+2] = (uchar) ((blocks[n]>>8));
     message[n+3] = (uchar) ((blocks[n]));
     // Printing works here; exact message comes back
     printf("%c%c%c%c", message[n], message[n+1], message[n+2], message[n+3]); 
}

But when I try to use the exact same code two lines later, it doesn't work.

for(n = 0; n < numBlocks; n++)
{
     // Printing doesn't work here.
     // Actually, the first letter works, but none of the others
     printf("%c%c%c%c", message[n], message[n+1], message[n+2], message[n+3]); 
}

I have tried printing out the characters in number format as well, and I can see that they have in fact changed.

What exactly is going on here? Is this undefined behavior? Does anyone have any reliable solutions? I'm not doing anything to change the value of the message array in between the two calls.

I'm running and compiling this on Sun 5.10 with a sparc processor.

È stato utile?

Soluzione

for(n = 0; n < numBlocks; n++) // Blocks are 32-bit unsigned ints (unsigned long)
{
     message[n] = (uchar) ((blocks[n]>>24));
     message[n+1] = (uchar) ((blocks[n]>>16));
     message[n+2] = (uchar) ((blocks[n]>>8));
     message[n+3] = (uchar) ((blocks[n]));
}

Every time you go through this loop, you set message[n] to message[n+3], then increment n by 1. This means that your first iteration sets message[0], message[1], message[2] and message[3], then your second sets message[1], message[2], message[3] and message[4]. So basically, you overwrite all but the first char in your message on every iteration.

Most likely you need to make message 4x larger and then do:

message[n*4] = ...
message[n*4 + 1] = ...
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top