0

I have just started looking at simple cryptography in order to learn python better. Encryptions and decryptions should be speedy and accurate so im hoping it will improve my programming skills.

I recently wrote this quick script for a shift cypher but i wasnt sure how to be able to define the shift.

import string
m = string.maketrans('abcdefghijklmnopqrstuvwxyz', 'pqrstuvwxyzabcdefghijklmno')

a = 'this should have been fairly easy to crack considering the length of the message'

n = string.maketrans('pqrstuvwxyzabcdefghijklmno', 'abcdefghijklmnopqrstuvwxyz')
x = string.translate(a, m)
print x

y = string.translate(x, n)
print y

for example if i shifter the letter a over 4 times it would be the letter e. I could make 26 encryption variables and 26 decryption variables but this isnt really pythonic or efficient. can anyone point me in the right direction?

Thanks for your time.

Edited by Archenemie: n/a

2
Contributors
3
Replies
4
Views
5 Years
Discussion Span
Last Post by Archenemie
0

What if i convert each character to its ASCII value and loop through the ASCII values?

Is this efficient?

1

The deque rotate function might be something to consider ...

# Caesar Cipher encryption/decryption
# using Python's double-ended queue

from collections import deque

def doCaesarCipher(text, shift):
    alpha = 'abcdefghijklmnopqrstuvwxyz'
    dq = deque(alpha)
    # shift/rotate the alphabet (dq in place)
    dq.rotate(shift)
    encrypted = ""
    for c in text.lower():
        if c in alpha:
            index_alpha = alpha.index(c)
            encrypted += dq[index_alpha]
        else:
            encrypted += c
    return encrypted


text = 'pumpkin'
# positive value shifts to the right
# negative value shifts to the left
shift = -5
encrypted = doCaesarCipher(text, shift)

print(text)       # pumpkin
print(encrypted)  # uzrupns

# shift to the right to get original text back
print(doCaesarCipher('uzrupns', 5))  # pumpkin

'abcdefghijklmnopqrstuvwxyz' can be obtained from module string.

Edited by vegaseat: string

0

To be honest thats perfect. I am going to move onto to "polyalphabetic substitution" cyphers and decyphers now. this should help alot :).

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.