I am trying to make a simple cryptography program using a simple subsitution method. If any one could help that would be nice. I need to be able to encode it as well as decode it. but im just a little confused on how to go about doing that.

here is the code so far.

""" crypto.py
    Implements a simple substitution cypher
"""

alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
key =   "XPMGTDHLYONZBWEARKJUFSCIQV"

def main():
  keepGoing = True
  while keepGoing:
    response = menu()
    if response == "1":
      plain = raw_input("text to be encoded: ")
      print encode(plain)
    elif response == "2":
      coded = raw_input("code to be decyphered: ")
      print decode(coded)
    elif response == "0":
      print "Thanks for doing secret spy stuff with me."
      keepGoing = False
    else:
      print "I don't know what you want to do..."

Recommended Answers

All 2 Replies

from string import maketrans
encode=lambda x: x.translate(maketrans(key,alpha))
decode=lambda x: x.translate(maketrans(alpha,key))

It only translates the characters you give in. So lowercase chars are not encoded and decoded.

If you on python3 than it wont work.

You could use a dictionary, on which you map every character from your alphabet with the key character:

def cryptography(text):
    alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz .,;'\"\\[]{}=-+*\|:<>?"
    key = "XPMGTDHLYONZBWEARKJUFSCIQVxpmgtdhlyonzbwearkjufsciqv .,;'\"\\[]{}=-+*\|:<>?"
    crypt, decrypt = {}, {} #dictionaries for crypting and decrypting
    for i, j in zip(alpha, key): crypt[i], decrypt[j] = j, i #fill up the dictionaries
    crypted = ''.join(crypt.get(i) for i in text) #encrypt text
    decrypted = ''.join(decrypt.get(i) for i in crypted) #decrypt text
    print crypted 
    print decrypted

And here's a generic example:

def main():
    text = "Aladdin had a ginny."
    cryptography(text)

main()

which would output this:

'''
Xzxggyw lxg x hywwq.
Aladdin had a ginny.
'''

But again, I don't know if this is what you thought to.

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.