为什么我的密码打印不正确?

时间:2015-11-16 07:03:18

标签: java encryption

我试图编写一个接受输入文件密码的程序,对其进行加密,然后在加密时将其保存到另一个文件中。到目前为止,我已经获得了创建文件的程序,并且密码中的每个字母都将替换该字母。问题是密码中的每个字母,我打印出密码而不是字母表中的字符。我想要输入我的密码" fallout"对于每个字母,更改是一个不同的随机字母。喜欢"后果"到" dfljsor"例如。我相信问题在于我的打印线,我该如何解决?

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class WriteFile {

    public static void main(String [] args) throws IOException {
        java.io.File inputFile = new java.io.File("inputFile.txt");
        java.io.File outputFile = new java.io.File("encrypted.txt");

        //create files and write to files
        try(Scanner input = new Scanner(inputFile);  
            PrintWriter output = new PrintWriter(outputFile);) {
            //creating array that holds the abc's
            //password is tombraider
            String key[] = { "q","w","r","t","u","i","o",
                             "p","a","s","d","f","g","h",
                             "j","k","l","z","x","c","v",
                             "b","n","m" };
            String key1[] = { "qwertyuiopasdfghjklzxcvbnm" };

            while (input.hasNext()) {
                String x = input.nextLine();

                //select a random char in key
                double number = Math.random() * 27;
                String index = key1.toString();
                char sort = index.charAt((int) number);

                // for each letter in the password, it is to be replaced with sort 
                for (int i = 0; i < x.length(); i++) {
                    char select = ((char) i);
                    output.print(x.replace(select, sort));
                }     
            } 
        }    
    }      
}

1 个答案:

答案 0 :(得分:1)

我没有足够高的代表评论(我的意思)。但似乎你正在使用x.replace(select, sort)。您已将x设置为整行。您可能打算做的事情是Character.toString(x.charAt(i)).replace(select, sort))或类似的事情。这样你就得到了每一个角色,而不是整条线。