0

I am having a little trouble attempting to reverse my encryption algorithm. The algorithm is a variation on the Caesar Cipher, and works like so:

(V1 + V2 + D) % 26 + 1

Where V1 is the letter of the phrase to be encrypted mapped to the relevant number (A = 1, etc), V2 is the letter of the users chosen key (the same length as the phrase), again mapped to the relevant number, and D is a chosen displacement value, ranging from 1 - 10.

The issue I am having is in attempting to reverse this. I have tried simply reversing the algorithm:

(V1 - V2 - D) % 26 - 1

but this obviously fails, due to the modulus involved. I have also attempted:

(V1 - V2 - D + 26) % 26

on the advice of here, but again this failed. It would be extremely helpful if somebody would be able to show me the solution to this, or at least point me in the correct direction.

1
  • You need to treat this as an equation, you can't simply switch + to - and hope for the best. Commented Jul 2, 2014 at 7:55

1 Answer 1

3
(v1 - v2 - d + 50) % 26 + 1

which is equivalent to

(v1 - v2 - d - 1 - 1 + 26 + 26) % 26 + 1

One of the - 1 is to compensate for the + 1 in the encryption. The other - 1 and the matching + 1 outside of the modulus is to wrap 0 back to 26 while leaving the rest untouched. And the reason for having 26 twice is simply that one 26 is not enough, since v1 - v2 - d - 1 - 1 can go down to 1 - 26 - 10 - 1 - 1, or -37.

import itertools

def encode(v1, v2, d):
    return (v1 + v2 + d) % 26 + 1

def decode(v1, v2, d):
    return (v1 - v2 - d + 50) % 26 + 1

all_combinations = map(tuple, itertools.product(
    range(1, 27), range(1, 27), range(1, 11)))

all(decode(encode(v1, v2, d), v2, d) == v1 for v1, v2, d in all_combinations)
# => True
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer, but I couldn't get this to work. When I tried it with V1 and V2 as 1 (A), the encryption is 7, which is a G. When I used that algorithm to decrypt, I ended up with 21, which is a U. Could you go over it again? Sorry for being a hassle.
I assume your d was 4 then (the only d that satisfies the result of 7: encode(1, 1, 4) == 7). Then, decode(7, 1, 4) == 1. When decoding, your V1 should be the encrypted character; running decode(1, 1, 4) does the wrong thing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.