0
// Converts Plain Text to Cipher Text


int key;
int prompt(void);
int enicpher(void);


// Takes User Command Line Arguments as Key if criteria are met
int main(int argc, string argv[])
{
    // Throws Error if there is not an arg provided or more than two
    if (argc != 2)
    {
        printf("Usage: ./casesar key\n");
        return 1;
    }
    else
    {
        // If arg is provided checks indiviual values
        for (int i = 0, n = strlen(argv[1]); i < n; i++)
        {
            // Throws error if not a number
            if (!isdigit(argv[1][i]))
            {
                printf("Usage: ./casesar key\n");
                return 1;
            }
        }
        // Convert digit to an int
        key = atoi(argv[1]);
        printf("Success\n%i\n", key);
        prompt();
        return 0;
    }
}

// Prompt user for plain text input and ouput cipher
int prompt(void)
{
    char cipher_digits;
    string text = get_string("plaintext: ");
    printf("ciphertext: ");
    // Loops over the plaintext and output cipher text
    for (int i = 0, n = strlen(text); i < n; i++)
    {
        cipher_digits = (text[i] + key);
        if (islower(text[i]))
        {
            printf("%c", ((cipher_digits - 'a') % 26) + 'a');
        }
        else if (isupper(text[i]))
        {
            printf("%c", ((cipher_digits - 'A') % 26) + 'A');
        }
        else
        {
            printf("%c", text[i]);
        }
    }
    printf("\n");
    return 0;
}


:( encrypts "barfoo" as "yxocll" using 23 as key
    expected "ciphertext: yx...", not "ciphertext: yx..."

:( encrypts "barfoo" as "onesbb" using 65 as key
    expected "ciphertext: on...", not "ciphertext: YX..."

:( encrypts "world, say hello!" as "iadxp, emk tqxxa!" using 12 as key
    expected "ciphertext: ia...", not "ciphertext: Sa..."
1

cipher_digits is of type char, more precisely 8-bit signed char, meaning it can store values from -128 to 127. What will happen if the sum is greater than 127? It will wrap around, interpreting the least significant byte of the result as char again, this time with a negative value (it's like 125, 126, 127, -128, -127).

A simple solution would be to make cipher_digits a type int, which can store much larger numbers.

Side note: This kind of wrap-around is pretty well-defined on our x86/amd64-based platform, but is not defined in the C standard (as 2's complement is not the only way to negate an integer, but now effectively everywhere), therefore standard-conforming C compilers can optimize away any checks that rely on this undefined behaviour.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .