Hi
I’m working with an old python exercise is to implement the caesar cipher, a simple encryption technique. Description of the methods can be found on the web (wikipedia) http://en.wikipedia.org/wiki/Caeser_cipher and the additional document.
In short, each letter is replaced by another letter (like a is replaced by b, b is replaced by c,. . . in case we are using a shift of one). You should write a python code who is able to crypt and decrypt an English sentence (the 26 letters) using this cipher. You program should take as input the size of the shift too (a number between 0 and 26).

How can I decrypt my message:) ?

message= raw_input("Please enter plaintext to Cipher: ")
shift = int(raw_input("Please enter shift: "))

result = ''
for letter in message:
    x = ord(letter)

    if letter.isalpha():
        x = x + shift

        offset = 65
        if letter.islower():
            offset = 97

        while x < offset:
            x += 26

        while x > offset+25:
            x -= 26

        result += chr(x)

print result

Decryption is the same as shifting by (26 - shift)

Thanks Sir,

where can I write in my code?

I got just gggg?maybe Im writting wrong?

result = ''
for letter in message:
    x = ord(letter)

    if letter.isalpha():
        x = 26 - shift

Output

Please enter your Cipher code: bcde
Please enter shift: 1
gggg

This seems to work ...

message = 'your mother wears army socks'
shift = 1

def cipher(message, shift):
    result = ''
    for letter in message:
        x = ord(letter)
        if letter.isalpha():
            x = x + shift
            offset = 65
            if letter.islower():
                offset = 97
            while x < offset:
                x += 26
            while x > offset+25:
                x -= 26
        result += chr(x)
    return result

encoded = cipher(message, shift)
decoded = cipher(encoded, -shift)

print encoded
print decoded

''' result..
zpvs npuifs xfbst bsnz tpdlt
your mother wears army socks
'''

Thanks Vegaseat Thanks ....
Vegaseat you are one of the my favorite person in daniweb:)

I guess this works as well:

def cipher(message, shift):
    return ''.join([chr(ord(i)+shift) if i.isalpha() else i for i in message])

Thanks Lucaci Andrew for different way.
What about if Im reading from a file(plaintext.txt) and wirte cipher to another file(cipher.txt)?

Well, you could open both files, read each line from the 'plaintext.txt', cipher it, than write it to the second file...

def fl(flin, flout, shift):
    try:
        [open(flout, 'a').write(cipher(i, shift)) for i in open(flin, 'r')]
    except Exception as e:
        print e

Thanks again

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.