-5

Built a C program that encrypts things using a Caesar Cipher. It converts it to an alphabetic number (0 = a / 1 = b / 2 = c) and then converts it pack after moving by the number of characters specified by using a modulo operator. I am currently trying to build a program the decrypts it and I need the exact opposite of a modulo operator to invert the sequence.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 5
    There is no opposite to modulo. Modulo maps multiple inputs to the same output, there's no way to know which input it originally was. – Barmar Aug 02 '17 at 20:27
  • E.g. `30 % 26` and `56 % 26` both result in `4`, there's no way to recover the original. – Barmar Aug 02 '17 at 20:28
  • 3
    " I am currently trying to build a program the decrypts it " --> post that code. – chux - Reinstate Monica Aug 02 '17 at 20:31
  • It seems your question has been answered, but if you need a helpful reference/ double check when you're all done, a copy of my working caesar cypher can be found [here](https://github.com/christopherdiehl/BlogPosts/blob/master/caesarCypher.c) – Turtle Aug 02 '17 at 20:39
  • Modulo is a one-way function. There is no reverse function for it. – m0h4mm4d Aug 02 '17 at 20:39
  • Reverse modulo? That sounds a bit like taking a burger and trying to retrieve the cow. – Gerhardh Aug 02 '17 at 21:25

1 Answers1

7

If you want to invert a Caesar cipher, you are not looking for the inverse of the modulo operator.

If your encryption is

int encrypt(int plaintext, int shift){
    int ciphertext = (plaintext + shift) % 26;
    return ciphertext;
}

Then decryption is

int decrypt(int ciphertext, int shift){
    int plaintext = (ciphertext - shift + 26) % 26;
    return plaintext;
}

for whatever your choice of shift was for encryption.

mattm
  • 5,851
  • 11
  • 47
  • 77
  • can you define exactly what you are using for C and P? (I am using e = (e + k)%26) and am just moving down the line with E as so I don't trip over variables – Jack Davies Aug 02 '17 at 20:37
  • Absolutely also double checked the math my self and found it to be 100% solid. I must have a messed up implementation in some place. I really appreciate the help. – Jack Davies Aug 02 '17 at 20:50
  • I had been testing it and while using small numbers it works wonderfully however when I put in a key such as 467467 it butchers the output and sends back a totally different string – Jack Davies Aug 02 '17 at 20:58
  • @JackDavies please post the [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) that shows the problem. Show the input, the expected output, and the actual output as text *in the question*. – Weather Vane Aug 02 '17 at 21:00
  • 1
    Note that the actual input to `encrypt` and `decrypt` is a number in the range of `[0, 26)`. The number represents a (plain or cipher) letter of the alphabet. – jxh Aug 02 '17 at 21:07