-1

I need to create a program that accepts a keyword from a .txt and then uses the keyword to create a cryptic alphabet. The alphabet I need takes the non-redundant letters of the key and places them at the front of the alphabet, then reverses the remaining alphabet. So if my keyword is "KEY", the new alphabet would be KEYZXWVUTSRQPONMLJIHGFDCBA. I then have to use the cipher alphabet to encrypt a sentence from another .txt.

I'm guessing I would need to use a bufferedReader instead of FileReader? Also, I hard coded the cipher alphabet but can't figure out how to accept a key from .txt to determine the cipher (like if the key changes, for example).

If someone could just give me a pointer or two on where to start, it would be greatly appreciated.

Here is some hard code I used:

package com.encryption.encryptionstring;


import java.util.*;
import java.io.*;
import java.nio.*;


public class MonoalphabeticEncryption
{

     public static char p[]  = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',

          'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',

          'w', 'x', 'y', 'z' };

     public static char ch[] = { 'T', 'R', 'O', 'Y', 'N', 'L', 'I', 'E', 'Z',

            'X', 'W', 'V', 'U', 'S', 'Q', 'P', 'M', 'K', 'J', 'H', 'G', 'F',

            'D', 'C', 'B', 'A' };





     public static String doEncryption(String s)

    {

        char c[] = new char[(s.length())];

        for (int i = 0; i < s.length(); i++)

        {

            for (int j = 0; j < 26; j++)

            {

                if (p[j] == s.charAt(i))

                {

                    c[i] = ch[j];

                    break;

                }

            }

        }

        return (new String(c));

    }


      public static String doDecryption(String s)

      {

           char p1[] = new char[(s.length())];

           for (int i = 0; i < s.length(); i++)

           {

               for (int j = 0; j < 26; j++)

               {

                   if (ch[j] == s.charAt(i))

                   {

                       p1[i] = p[j];

                       break;

                   }

               }

           }

           return (new String(p1));

       }

       public static void main(String args[])

       {

           Scanner sc = new Scanner(System.in);

           System.out.println("Enter the message: ");

           String en = doEncryption(sc.next().toLowerCase());

           System.out.println("Encrypted message: " + en);

           System.out.println("Decrypted message: " + doDecryption(en));

           sc.close();

       }


 }

EDIT: I started making updates per Z. Bagley's suggestion. Here is what I have so far, an alphabet array, accepted my input.txt and keyword.txt to arrays:

package com.encryption.encryptionstring;


import java.util.*;
import java.io.*;
import java.nio.*;


public class MonoalphabeticEncryption
{
   char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray(); //is this a good alphabet array? How do I compare one array to another?

   private String readFileKeyword(String file) throws IOException 
   {
       FileWriter fileOutput= new FileWriter("output.txt");
       BufferedReader readerKeyword = new BufferedReader(new FileReader ("keyword.txt"));
       String         lineKeyword = null;
       StringBuilder  stringBuilderKeyword = new StringBuilder();
       String         lsKeyword = System.getProperty("line.separator");

       try 
       {
           while((lineKeyword = readerKeyword.readLine()) != null) 
           {
               stringBuilderKeyword.append(lineKeyword);
               stringBuilderKeyword.append(lsKeyword);
               System.out.println(fileOutput);//will this print text from keyword.txt to output.txt?
           }

           return stringBuilderKeyword.toString();

       } 
       finally 
       {
           readerKeyword.close();
       }

   }

   private String readFileInput(String file) throws IOException
   {
       BufferedReader readerInput = new BufferedReader(new FileReader ("input.txt"));
       String         lineInput = null;
       StringBuilder  stringBuilderInput = new StringBuilder();
       String         lsInput = System.getProperty("line.separator");

       try 
       {
           while((lineInput = readerInput.readLine()) != null) 
           {
               stringBuilderInput.append(lineInput);
               stringBuilderInput.append(lsInput);
               System.out.println(stringBuilderInput); //will this print text from input.txt?
           }

           return stringBuilderInput.toString();
       } 
       finally 
       {
           readerInput.close();
       }
    }

}
sfrank
  • 3
  • 1
  • 6
  • So, how many keywords your text file will include? do you want to encrypt each sentence per keyword ? – FSm Apr 30 '17 at 17:28
  • I'm trying to encrypt and decrypt strings using cipher text with a random keyword. The random keyword will be in a file "keyword.txt": TROYONLINE The string(s) will be in a separate file "input.txt": THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG The cipher should use the keyword and a reversed alphabet without redundant letters. The cipher for keyword "TROYONLINE" would be: TROYNLIEZXWVUSQPMKJHGFDCBA The cipher should use the keyword and a reversed alphabet without redundant letters. The cipher for keyword "TROYONLINE" would be – sfrank May 01 '17 at 14:20
  • the above comment is done, just clarifying the question. now I have read an input text file to a charArray, and converted the cipher to a charArray, I just can't figure out how to replace a specific character from the input charArray with a charArray from a specific index in the cipher array – sfrank May 01 '17 at 14:22
  • Add additional information to the question, not a comment, so all relevant information is in one place. That also allows formatting. Then delete the comments. – zaph May 01 '17 at 18:29
  • See my answer for generating crypto key – FSm May 02 '17 at 13:56

2 Answers2

1

First read the txt to a string: How do I create a Java string from the contents of a file?

Swap it to a string array: string to string array conversion in java

Remove duplicates: How to efficiently remove duplicates from an array without using Set

After that, append items that don't already exist in the array in reverse order. (You'll have to compare the alphabet array to your keyword array in a loop).

That will give you your new cipher code array! the next part is translating other words to your cipher language. This part takes the same steps as the first two. Then all you need to do is compare each letter of your new array to its index in your alphabet array, and then use those indices to translate to your cipher.

Hope this gives you an understanding of where to start, and best of luck.

Community
  • 1
  • 1
Z. Bagley
  • 8,942
  • 1
  • 40
  • 52
  • I created a string in a privte String readFile using a buffered reader, just like the example link you posted. So to convert the string to a string array, can I do it in the same private method or do I need to create another method to handle this? If new, how do I reference the private the string that was just created? Thanks! – sfrank Apr 28 '17 at 01:40
0

For reading file and generating your cripto key, try this

1- Read your keyword to string.

2- Create a string of [a..z] alphabet.

3- For each char of keyword, loop through the alphabet string and replace that char with "".

4- Concatenate the keyword string with the rest of the alphabet string.

5- Apply your encryption and decryption as you need (I Will keep this for you to try).

The below code is for generating the crypto key as your asked.

public static void main(String[] args) throws IOException {

String text = new String(Files.readAllBytes(Paths.get("keyword.txt")),UTF_8);
text= generateKey(text);

System.out.println(text);


}

public static  String  generateKey(String k)
{
String alpha = "abcdefghijklmnopqrstuvwxyz"; 
String [] key = k.split("");

for (int i=0; i<key.length;i++)
    {
         alpha = alpha.replaceAll(key[i],"");
    }
  StringBuilder sb = new StringBuilder(alpha);

  return k + sb.reverse()  ;   

}

Assume your keyword is "key", so the output would be

 "keyzxwvutsrqponmljihgfdcba"

Be sure that you are importing below

import java.io.IOException;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.nio.file.Files;
import java.nio.file.Paths;
FSm
  • 2,017
  • 7
  • 29
  • 55