Skip to content

Instantly share code, notes, and snippets.

@tmitzka
Last active February 11, 2018 10:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmitzka/2d139cd349fc0886ca0fd81902105cb3 to your computer and use it in GitHub Desktop.
Save tmitzka/2d139cd349fc0886ca0fd81902105cb3 to your computer and use it in GitHub Desktop.
Encrypts a message using a Caesar cipher.
#!/usr/bin/env python3
"""Encrypts a message using a Caesar cipher.
https://en.wikipedia.org/wiki/Caesar_cipher
"""
from string import ascii_uppercase
class Caesar():
def __init__(self, shift):
self.shift = shift
self.letters = ascii_uppercase
def __repr__(self):
return "Performs a Caesar encryption."
def get_message(self):
print("Enter message:")
message = input().upper()
return message
def encrypt(self, message):
cipher = ""
# Special characters don't get encrypted.
# find() returns -1 if a string is not contained
# in the letters from A-Z.
for character in message:
index = self.letters.find(character)
if index == -1:
cipher += character
else:
cipher_index = index + shift
# After Z, start again from A:
if cipher_index > 25:
cipher_index -= 26
cipher += self.letters[cipher_index]
return cipher
# Set cipher shift (max. 25).
shift = 3
c = Caesar(shift)
message = c.get_message()
cipher = c.encrypt(message)
print("\nEncrypted message:")
print(cipher)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment