Mickey
Mickey

Reputation: 127

Caesar shift cypher

I'm working on a simple Caesar Cipher in python using chr() and ord()

Here's my code:

 key = 13
 newString = ''
 if mode == 'decrypt':
     key = -key
 for c in message:
     newString += chr(ord(c) + key)
 print newString

But something funny happens!

When I input: "Hello world!", I get back "Uryy|-?|yq."

Looks about right, right?

But when I try deciphering it,

I get: Hello 2old!

Any insights? I'm thinking it has to do with chr() returning something like this: '\x84'

Upvotes: 2

Views: 757

Answers (1)

lewisjb
lewisjb

Reputation: 686

"Hello world!" is 12 characters, but "Uryy|-?|yq." is 11 (and so is "Hello 2old!").

The cause of this is that the new ASCII code of the w is 132 instead of 119. Which is the '\x84' code.

If you do it in the IDLE and instead of print just type the variable, it outputs the string with \x84, but if you print it, it replaces it with an invalid character. If you input the exact string (with the \x84) it returns "Hello world!". If you don't understand the \x84 I suggest you research character codes and hexadecimal.


And a traditional Caesar shift keeps all characters as letters, not others, like punctuation marks, pipes and 132.

  • A has the character code of 65 (in decimal)

  • a is 97

According to http://en.wikipedia.org/wiki/Caesar_cipher, the encryption and decryption are:

"E_n(x) = (x + n) \mod {26}."

and

"D_n(x) = (x - n) \mod {26}."

respectively.

Use the character offsets of 65 and 97 and do what the Wikipedia article says.

Upvotes: 4

Related Questions