程序未正确加密

时间:2015-04-17 19:55:27

标签: java

我正在开发一个程序,它接受用户输入(输入txt文件,要移位的空格数,移位方向,以及他们想要创建的output.txt文件的名称)。我的程序正在编译,当我运行它时,它会创建一个输出文件,但结果不是它们应该是什么。例如,如果我将其设置为以3的移位加密并且方向是正确的,则单词The应该更改为WKH。目前,我还没有实现方向,因为我似乎无法弄清楚如何向左移动。任何人都可以如此善良地查看我的代码并帮助指导我走向正确的方向吗?非常感谢你的时间!

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

public class CaeserCipher {

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

        String originalText="";
        String inputFile;
        String outputFile = "";
        String shiftDirection;
        int shiftValue;
        Scanner keyboard = new Scanner(System.in);

        //Prompt user for input file name
       Scanner in = new Scanner(System.in);
       System.out.print("What is the filename?: ");
       inputFile = in.nextLine();


       //make sure file does not exist
            File file = new File(inputFile);
               if (!file.exists())
               {
                  System.out.println("\nFile " + inputFile + " does not exist. File could not be opened.");

                  System.exit(0);
               }

         //send the filename to be read into String

         originalText = readFile(inputFile);


         //Prompt user for shift value
         System.out.print("\nWhat is the shift value? ");
         shiftValue = keyboard.nextInt();

         //Prompt user for shift direction
         Scanner sc = new Scanner(System.in);
         System.out.print("What direction would you like to shift? Press L for left or R for right: ");

         //validate the input
         while (!sc.hasNext("[LR]")) {
             System.out.println("That's not a valid form of input! Please enter only the letter 'L' or 'R': ");
             sc.next();
             shiftDirection = sc.next(); //stores the validated direction
         }//end while

         shiftDirection = sc.next(); //stores the validated direction

         //Return encrypted string
         String encryptedText = encrypt(originalText , shiftValue);

         //get the outputfile name
         System.out.print("What is the name of the output file you want to create?: ");
         outputFile = in.nextLine();

         //make sure file does not exist
         File file2 = new File(outputFile);
            if (file2.exists())
            {
               System.out.println("\nFile " + outputFile + " already exists. Output not written.");

               System.exit(0);
            }

        try {
            File file3 = new File(outputFile);
            BufferedWriter output = new BufferedWriter(new FileWriter(file3));
            output.write(encryptedText);
            output.close();
        } catch ( IOException e ) {
            e.printStackTrace();
        }
        System.out.println("\nOutput written to " + outputFile);        

    } //end main

    //rotate and change chars
    public static String rotate(String userString, int shiftValue) {

        String convertedText = "";
        for(int i = 0; i < userString.length(); i++){
        char lowerLetter = userString.charAt(i);

        //Convert to uppercase
        char upperLetter = Character.toUpperCase(lowerLetter);
        int charNumber = upperLetter;

        //Apply shift, remembering to wrap text
        int rotateShift = (charNumber + shiftValue) % 26;
        char shiftLetter = (char) rotateShift;

        //Create new string of shifted chars
        convertedText += shiftLetter;
        }
      return convertedText;
    }

    //encrypt
    public static String encrypt(String userString, int shiftValue) {
        String encryptedString = rotate(userString , shiftValue);
        return encryptedString;
    }

    private static String readFile(String inputFile) throws java.io.IOException {
      File file = new File(inputFile);
      StringBuilder fileContents = new StringBuilder((int) file.length());
      Scanner scanner = new Scanner(new BufferedReader(new FileReader(file)));
      String lineSeparator = System.getProperty("line.separator");

         try {
             if (scanner.hasNextLine()) {
                 fileContents.append(scanner.nextLine());
             }
             while (scanner.hasNextLine()) {
                 fileContents.append(lineSeparator + scanner.nextLine());
             }

         return fileContents.toString();
    }


     finally {
        scanner.close();
    }

 }
}

1 个答案:

答案 0 :(得分:4)

您的问题是%26。您没有考虑ASCII字符的工作原理。你需要这样做:

int rotateShift = ((charNumber - 'A' + shiftValue) % 26) + 'A';

之前你做的是错误的,因为char是一个ASCII值。这意味着'A' == 65因此要将字符表示形式转换为数字,您应首先从字符值中追溯'A'。这映射A->0, B->1, C->2, ...。然后,当您完成Caesar Shift时,需要将'A'的值添加回整数以将其重新转换为ASCII字符。

您可能还遇到了Java的%运算符的另一个问题。 Java的模块化运算符的操作如下:

-4 % 5 == -4

因此我会写一个加密mod函数:

public int crypto_mod(int num, int mod)
{
    num %= mod;
    if(num < 0) num += mod;
    return num;
}

这应该产生你正在寻找的角色。