473,586 Members | 2,639 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Cipher/decipher program

2 New Member
I'm trying to make a simple program that will convert to and from a cipher that's already set.

Expand|Select|Wrap|Line Numbers
  1. foo = 'a = hz\nb = ye\nc = uo\nd = pd\ne = qi\nf = jy\ng = ru\nh = sw\ni = ln\nj = ae\nk = na\nl = rt\nm = wu\nn = is\no = nd\np = hw\nq = op\nr = kb\ns = vf\nt = fc\nu = xr\nv = ex\nw = mn\nx = gb\ny = bu\nz = ie\n. =  *right wing slash* \n, =  *hand wave* \n" =  *hand curve* \n! =  *double hand jerk* \n? =  *wing wave* \n... =  *squiggly hand motion* '
  2. repl={}
  3. reverse_repl={}
  4. import sys
  5. #Generate replacement tables
  6. for str in foo.split("\n"):
  7.     parts=str.split(" = ")
  8.     repl[parts[0]]=parts[1]
  9.     repl[parts[0].lower()]=parts[1]
  10.     reverse_repl[parts[1]]=parts[0]
  11. def encipher():
  12.     outstr = ''
  13.     instr = sys.stdin.readline()
  14.     i = 0
  15.     for i in range(len(instr)):
  16.         c = instr[i]
  17.         if (instr[i:i+3]=='...'):
  18.             outstr+=repl['...']
  19.             i+=3
  20.         else:
  21.             if (c in repl):
  22.                 outstr+=repl[c]
  23.                 i+=1
  24.             else:
  25.                 outstr+=c
  26.                 i+=1
  27.     print outstr
  28. def decipher():
  29.     outstr = ''
  30.     instr = sys.stdin.readline()
  31.     instr=instr[:-1]
  32.     i = 0
  33.     c = instr[i]
  34.     while (i<len(instr)):
  35.             if (instr[i:i+2]):
  36.                 outstr+=reverse_repl[instr[i:i+2]]
  37.                 i+=2
  38.             else:
  39.                 outstr+=c
  40.                 i+=1
  41.     print outstr
  42. if (sys.argv[1]=="-e"):
  43.     encipher()
  44. else:
  45.     decipher()
  46. raw_input('press Return to end program>')
Couple of things I couldn't get working:
  1. I couldn't separate the '...' from the '.' The '...' will give the correct equivalent from the list when enciphering, but will also follow it with 2 instances of '.'
  2. For deciphering, it works up until it goes up against a character that's not in "foo" like 123 or a space.

Thanks for your help in advance.
Dec 14 '08 #1
4 6732
bvdet
2,851 Recognized Expert Moderator Specialist
It appears that you want to replace each character with a unique 2 character string with a special exception for "...". I don't understand what *squiggly hand motion* is, but I'll assume that it is 2 characters. If a character is not in repl, double it so we be consistent.

Your code:
Expand|Select|Wrap|Line Numbers
  1.     for i in range(len(instr)):
  2.         c = instr[i]
  3.         if (instr[i:i+3]=='...'):
  4.             outstr+=repl['...']
  5.             i+=3
  6.         else:
  7.             if (c in repl):
  8.                 outstr+=repl[c]
  9.                 i+=1
  10.             else:
  11.                 outstr+=c
  12.                 i+=1
Variable i is updated each iteration. If you assign i in the body of the loop, you will lose the assignment.
Try the following instead:
Expand|Select|Wrap|Line Numbers
  1.     while i < len(instr):
  2.         c = instr[i]
  3.         if instr[i:i+3] == '...':
  4.             outstr += repl['...']
  5.             i+=3
  6.         elif c in repl:
  7.             outstr += repl[c]
  8.             i+=1
  9.         else:
  10.             outstr += c*2
  11.             i+=1


To get the code to work, I replaced your code:
Expand|Select|Wrap|Line Numbers
  1.     while (i<len(instr)):
  2.             if (instr[i:i+2]):
  3.                 outstr+=reverse_repl[instr[i:i+2]]
  4.                 i+=2
  5.             else:
  6.                 outstr+=c
  7.                 i+=1
with the following code:
Expand|Select|Wrap|Line Numbers
  1.     while i<len(instr):
  2.         if reverse_repl.has_key(instr[i:i+2]):
  3.             outstr += reverse_repl[instr[i:i+2]]
  4.         else:
  5.             outstr += instr[i][0]
  6.         i+=2
There were several places in your code where parentheses were not required. Avoid using str as a variable name, because the built-in function str() will be masked.
HTH --BV
Dec 14 '08 #2
slurpz
2 New Member
Thanks for the quick reply. I actually worked a bit on my code while I waited so my code looks pretty similar to yours. My code looks like this right now:

Expand|Select|Wrap|Line Numbers
  1. foo = 'a = hz\nb = ye\n... =  *squiggly hand motion* \nc = uo\nd = pd\ne = qi\nf = jy\ng = ru\nh = sw\nI = xegy\ni = ln\nj = ae\nk = na\nl = rt\nm = wu\nn = is\no = nd\np = hw\nq = op\nr = kb\ns = vf\nt = fc\nu = xr\nv = ex\nw = mn\nx = gb\ny = bu\nz = ie\n. =  *right wing slash* \n, =  *hand wave* \n" =  *hand curve* \n! =  *double hand jerk* \n? =  *wing wave* '
  2. repl={}
  3. reverse_repl={}
  4. import sys
  5. #Generate replacement tables
  6. for str in foo.split("\n"):
  7.     parts=str.split(" = ")
  8.     repl[parts[0]]=parts[1]
  9.     repl[parts[0].lower()]=parts[1]
  10.     reverse_repl[parts[1]]=parts[0]
  11. def encipher():
  12.     outstr = ''
  13.     instr = sys.stdin.readline()
  14.     i = 0
  15.     n = len(instr)
  16.     while i < n:
  17.         c = instr[i] 
  18.         if instr[i:i+3] == '...': 
  19.             outstr += repl['...'] 
  20.             i+=3 
  21.         elif c in repl: 
  22.             outstr += repl[c] 
  23.             i+=1 
  24.         else: 
  25.             outstr += c
  26.             i+=1
  27.     print outstr
  28. def decipher():
  29.     outstr = ''
  30.     instr = sys.stdin.readline()
  31.     i = 0
  32.     n = len(instr)
  33.     while i < n:
  34.         if instr[i:i+2] in reverse_repl:
  35.             outstr+=reverse_repl[instr[i:i+2]]
  36.             i+=2
  37.         else:
  38.             outstr+=instr[i]
  39.             i+=1
  40.     print outstr
  41. if (sys.argv[1]=="-e"):
  42.     encipher()
  43. else:
  44.     decipher()
  45. raw_input('press Return to end program>')
Enciphering works perfectly (that "..." fix was great), but now with deciphering, there are a couple values that take up more than 2 letters.

These include:
*right wing slash* = .
*hand wave* = ,
*hand curve* = "
*double hand jerk* = !
*wing wave* = ?
*squiggly hand motion* = ...
xegy = I

Is there a more efficient way than searching for each one individually? (Maybe from an array or something?)
Dec 14 '08 #3
bvdet
2,851 Recognized Expert Moderator Specialist
You should consider processing these special cases separately. Example:
Expand|Select|Wrap|Line Numbers
  1. dd = {'*right wing slash*': '.',
  2.       '*hand wave*': ',',
  3.       '*hand curve*': '"',
  4.       '*double hand jerk*': '!',
  5.       '*wing wave*': '?',
  6.       '*squiggly hand motion*': '...',
  7.       'xegy': 'I'}
  8.  
  9. def fix_str(s):
  10.     for key in dd:
  11.         s = s.replace(key, dd[key])
  12.     return s
Expand|Select|Wrap|Line Numbers
  1. >>> print fix_str("*right wing slash**hand wave**hand curve*")
  2. .,"
  3. >>> 
Dec 14 '08 #4
MojaveKid
9 New Member
2 digit encryption...th e closest thing to this will be the BIFID cipher

try reading this: http://en.wikipedia.org/wiki/Bifid_cipher

it should give you a good idea on the algorithm
Mar 2 '09 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

6
6563
by: Michael Sparks | last post by:
Hi, I suspect this is a bug with AMK's Crypto package from http://www.amk.ca/python/code/crypto , but want to check to see if I'm being dumb before posting a bug report. I'm looking at using this library and to familiarise myself writing small tests with each of the ciphers. When I hit Crypto.Cipher.ARC4 I've
4
8028
by: Carl Harris | last post by:
I am trying to write some code to: 1.Prompt a user for filenames 2.Open the files 3.Convert my plain text into a cipher text array/string bear in mind I am a novice! I have wriiten some code already which completes takes 1 and 2 but haven't got a clue with the conversion (task 3)
7
6819
by: Piotr Turkowski | last post by:
Hi! Here you can get some notes about Vigenere Cipher: http://raphael.math.uic.edu/~jeremy/crypt/vignere.html Here's whole code of my program, function stats() is in polish, so you can omit it. The problem is that the encrypting function is not working correctly, so I didn't write decryptying function. Plz, can you help me with both...
9
3718
by: Piotr Turkowski | last post by:
Hi, The code is here: http://free.ud.pl/~piotr/data/vigenere.zip Its my program for decrypting and encrypting text. Shot polish course: szyfrowanie (szyfruj) - encrypting (text i want to code -> (*(^%&^GHJBBVvkek) odszyfrowanie (deszyfrowanie) - decrypting ( *^BNHJ*&% - > secret text) obsluga plikow - using files
1
5422
by: mkazek | last post by:
hi, where i can find source codes to encipher/decipher files with Hill's cipher and Transpositon Cipher?? (preferably vc++ source code)
2
7278
by: Julio C. Hernandez Castro | last post by:
Dear all, We have just developped a new block cipher called Raiden, following a Feistel Network structure by means of genetic programming. Our intention now consists on getting as much feedback as possible from users, so we encourage you to test the algorithm and send us your opinion. We would also like to receive enhancements and new...
1
7724
by: beetle17 | last post by:
Plaintext: a  n i c e  d a y Key: -3 Ciphertext: X  k f Z b  a X v Cipher will accept commands from the user and perform the operations required by the commands. There are three different commands. Key command starts with "K1:"followed by a string as the key. Encryption command starts with "E1:" followed by the plaintext. Decryption...
16
3955
by: Cawas | last post by:
Cipher Lab produces some terminals to collect data where we can program using one implementation of plain C which I believe to be ANSI C89 compatible, although not fully. They have their on set of libraries as well, but all in all, it's basic C we're talking about. Ok, this is my first time on lots of things. I've never been to usenet, and...
4
10197
by: wagn31 | last post by:
i need to use a cipher but I have to used the assigned code in the ciphering i know how to do it, but i am not sure how to add my own dictionary. Here is what i have so far:
0
7912
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7839
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8202
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7959
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6614
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5390
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3837
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2345
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1449
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.