-1

I am creating a simple encryption program. I am adding chars to chars to create a new char.

As of now the new 'char' is often a represented by a '?'.

My assumption was that the char variable has a max sum and once it was passed it looped back to 0.

assumed logic:

if char a == 1 && char z == 255 then 256 should == a.

This does not apear to be the case.


This snippet adds a char to a char. It often prints out something like:

for (int i = 0; i < half; ++i) {
    halfM1[i] = halfM1[i] + halfP1[i];
    halfM2[i] = halfM2[i] + halfP2[(half + i)];
}

printf("\n%s\n", halfM1 );
printf("%s\n", halfM2);

Returns:

a???

3d??

This snippet removes the added char and the strings go back to normal.

for (int i = 0; i < half; ++i) {
    halfM1[i] = halfM1[i] - halfP1[i];
    halfM2[i] = halfM2[i] - halfP2[(half + i)];
}

printf("\n%s\n", halfM1 );
printf("%s\n", halfM2);

returns:

messagepart1
messagepart2

The code technically works, but I would like the encryption to be in chars.

If question on why 'half' is everywhere. The message and key are split in half so the first half and second half of message have separate encryption.

seamus
  • 2,681
  • 7
  • 26
  • 49

1 Answers1

1

First of all, there is no such thing as "wraparound" for common char. A common char is a signed type in x86, and signed integers do not have wraparound. Instead the overflow leads to undefined behaviour. Additionally, the range of chars can be -128 ... 127, or even something

For cryptographic purposes you'd want to use unsigned chars, or even better, raw octets with uint8_t (<stdint.h>).

Second problem is that you're printing with %s. One of the possible 256 resulting characters is \0. If this gets into the resulting string, it will terminate the string prematurely. Instead of using %s, you should output it with fwrite(halfM1, buffer_size, 1, stdout). Of course the problem is that the output is still some binary garbage. For this purposes many Unix encryption programs will write to file, or have an option to output an ASCII-armoured file. A simple ASCII armouring would be to output as hex instead of binary.

The third is that there is an operation that is much better than addition/subtraction for cryptographic purposes: XOR, or halfM1[i] = halfM1[i] ^ halfP1[i]; - the beauty of which is that it is its own inverse!