试图用Java制作Vigenere加密器

时间:2018-03-08 01:56:46

标签: java vigenere

EDIT2:猜猜问题就在这里。所以我的第一个问题是,我是否正确扫描文件(可能不是)?

所以我尝试使用Vigenere密码在Java中构建编码器。假设密钥和纯文本文件在执行程序时在命令行中传递(例如“> java vigenere k1.txt pt1.txt”)。然后它假设扫描文件中的文本(这是我认为我没做的部分之一),它将删除所有非字母字母并将所有文本转换为较低的文本,每个(键和纯文本),如果短文比短文重复,则用“x”填充明文。它从那里开始通过将字符移动到关键字符%26来加密纯文本。

import java.util.Scanner;

public class vigenere {

    //string length constant
    public static final int MAX_LENGTH = 512;    

    public static void main(String[] args) {
        //obtaining file names
        String keyFile = args[0];
        String plainTextFile = args [1];

        //scanning files
        Scanner keyContents = new Scanner(keyFile);
        keyContents.useDelimiter("//Z");
        Scanner plainTextContents = new Scanner(plainTextFile);
        plainTextContents.useDelimiter("//Z");

        //turn scanners into strings
        String key = keyContents.next();
        String plainText = plainTextContents.next();

        //conver string to stringbuilder
        StringBuilder key1 = new StringBuilder(key);
        StringBuilder plainText1 = new StringBuilder(plainText);

        //set length of strings
        key1.setLength(MAX_LENGTH);
        plainText1.setLength(MAX_LENGTH);

        //set stringbuilder back to string
        key = key1.toString();
        plainText = plainText1.toString();

        System.out.println("Original Key:");
        System.out.println(key);
        System.out.println("****************************");
        System.out.println("Original PlainText:");
        System.out.println(plainText);
        System.out.println("****************************");

        encrypt(plainText, key);
    }

    static void encrypt(String plainText, String key) {
        //new strings
        String newKey = "";
        String newPlainText = "";

        //convert to all lowercase
        key = key.toLowerCase();
        plainText = plainText.toLowerCase();

        for(int i=0; i<key.length(); i++) {
            char currentKey = key.charAt(i);
            if(currentKey < 'a' || currentKey > 'z')
                continue;
            newKey += (char)(currentKey);
        }

        System.out.println(newKey);

        for(int i=0, j=0; i<plainText.length(); i++) {
            char currentPlainText = plainText.charAt(i);
            if(currentPlainText < 'a' || currentPlainText > 'z')
                continue;
            newPlainText += (char)((currentPlainText + newKey.charAt(j) % 26) + 'A');
        }

        System.out.println(newPlainText);
    }
}

目前的输出是:

Original Key:
k1.txt
****************************
Original PlainText:
p1a.txt
****************************
ktxt
´¥¸¼¸

0 个答案:

没有答案