0
votes

I am working on an encryption/decryption code for C. Whilst I have the code encrypting and decrypting well enough there are still some errors. I want the users input to be in between '!' (ASCII value 32) and '~' (ASCII value 126), However, when the user puts in a character such as '~' with a fairly highly offset/key-value the output is in the extended ASCII characters range. Is there any way that I can force the output to not be in the extended character range and still decrypt/encrypt properly?

I have messed around with changing the values for "cipher" but it hasn't helped too much.

Below is my code

    void Encryption(char* OriginalText, int offset) {
    int i = 0;
    int cipher;
    char encrypt;
    printf("Encrypted string: \n");
    while (OriginalText[i] != '\0') {
        if (OriginalText[i] == ' ') {
            encrypt = ' ';
            printf("%c", encrypt);
            i = i + 1;
        }

        cipher = ((int)OriginalText[i] + (offset % 26) % -26);
        encrypt = (char)(cipher);
        printf("%c", encrypt);

        i = i + 1;
    }
    printf("\n");
}
2
The usual strategy is to only shift letters and to leave all other characters as they are. (By the way, shouldn't there be an else to your if?) You could also rotate over a wider range; shifting from '!' to '~' is what rot47 does, for example. In that case, some letters will turn into symbols and vice versa. If the range is [min, min + n) and if 0 ≤ offset < n, then new = min + (old - min + offset) % n. - M Oehm
Your cipher does not match Caesar cipher - David C. Rankin
It's not your question, but the code has a buffer overflow, for example if OriginalText is "hello ". - Paul Hankin

2 Answers

0
votes

The '%' operator has higher precedence than the '+'. Therefore, it applies on the result of the exprssion offset % 26 first, and then added to OriginalText[i].

In order to fix this, you should add another pair of parenthesis in the assignment to cipher:

cipher = (((int)OriginalText[i] + (offset % 26)) % -26);

Moreover, when you're dealing with ASCII characters, just to walk on the safe side and prevent annoying and unwanted bugs, you should treat your I/O as unsigned char, hence:

unsigned char cipher;
unsigned char encrypt;
...
cipher = ((OriginalText[i] + (offset % 26)) % 26);
encrypt = cipher;
0
votes

You should first convert your character to an index between zero and the size of the alphabet (exclusive), i.e. from 0 to 25 for the ABC. Only then do the modular addition / subtraction. Finally, convert back. The best way to do this is to simply perform character - 'a' (in case of lowercase characters of course). Do not perform modular operations on ASCII values itself.