1. Engineering
  2. Computer Science
  3. a ruby program problem simple substitution cypher a...

Question: a ruby program problem simple substitution cypher a...

Question details

a ruby program problem

*****************************************************************

Simple Substitution Cypher -

A simple substitution cypher is a way to encrypt messages from easily being read by using a one-to-one substitution of characters in a text. To begin, we need to know the substitution function. Here is an example:


alphabet: abcdefghijklmnopqrstuvwxyz

cipher: zyxwvutsrqponmlkjihgfedcba


In this case, I've just reversed the order of the alphabet. However, the way it's used as a substitution, the 'a' in the text will be substituted for a 'z'. The 'b' in the text will be substituted for a 'y', and so on. One of the requirements is that the cipher must be reversible, so the cipher need a reverse mapping as well. One has to also map uppercase letters, but we will do the substitution and preserve the case in the text. So here is an example of the original text and the encrypted text.


original: Ruby is a fun language!

encrypted: Ifyb rh z ufm ozmtfztv!


Notice that the uppercase 'R' is substituted with an uppercase 'I'. Your program needs to preserve the case of the substitution.


Now, we are going to use an encryption key to create the cipher in our program. To do this you need to select a word to create the cipher. If I use the word 'honey', then the cipher becomes:


cipher: honeyabcdfgijklmpqrstuvwxz


The word used in this cipher must not have any repeating characters. We could fix that but for this solution, we will just insist on this property of the key.


Your job is to create a Ruby program that will take a key word and a text file then print out the encrypted text message. For instance, here is a run of the program:


> encrypt

Enter the cipher key > honey

Enter the text file > mythoughts.txt

Enter the encrypted file > mysecret.txt


> encrypt -d

Enter the cipher key > honey

Enter the encrypted file > mysecret.txt

Enter the text file > mythoughts.txt


In the above examples of execution, the first encrypts the file 'mythoughts.txt' to 'mysecret.txt' using the key 'honey' to create the cipher. The second execution decrypts the message in 'mysecrets.txt' using the key 'honey' to create the cipher then writing the deciphered text in 'mythoughts.txt'. Realize that when decrypting, we are reversing the roles of the cipher and the alphabet in substitution for the text. When we encrypt the message, the alphabet character in the text is substituted using the cipher character, but when we decrypt the message, the cipher character in the encrypted text is substituted using the alphabet character.

Solution by an expert tutor
Blurred Solution
This question has been solved
Subscribe to see this solution