java 我的维杰内尔密码无法解密,谁能看出我的代码有什么问题吗?

k97glaaz  于 2023-05-05  发布在  Java
关注(0)|答案(1)|浏览(164)

我用java做了一个vigenere密码。加密工作正常,但我无法解密。这是我的代码

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Do you want to encrypt or decrypt? (E/D): ");
        String mode = scanner.nextLine().toUpperCase();
        System.out.print("Input file name: ");
        String inputFileName = scanner.nextLine();
        System.out.print("Output file name: ");
        String outputFileName = scanner.nextLine();
        System.out.print("Keyword (all capitals): ");
        String keyword = scanner.nextLine().toUpperCase();
        scanner.close();
        
        try {
            BufferedReader reader = new BufferedReader(new FileReader(inputFileName));
            BufferedWriter writer = new BufferedWriter(new FileWriter(outputFileName));
            
            int keywordIndex = 0;
            String line = reader.readLine();
            while (line != null) {
                for (int i = 0; i < line.length(); i++) {
                    char c = line.charAt(i);
                    if (Character.isLetter(c)) {
                        int shift = keyword.charAt(keywordIndex) - 'A';
                        if (mode.equals("D")) {
                            shift = 26 - shift;
                        }
                        else {
                        c = (char)(((c + shift - 'A') % 26) + 'A');
                        keywordIndex = (keywordIndex + 1) % keyword.length();
                        c = Character.toUpperCase(c);
                        }
                    }
                    writer.write(c);
                }
                writer.newLine();
                line = reader.readLine();
            }
            reader.close();
            writer.close();
            
            System.out.println("Done.");
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

除了解密部分,代码的所有部分都运行正常。由于某种原因,它无法解密。它也创建了我的输出文件,但加密是1相同的或2再次加密。

igetnqfo

igetnqfo1#

最里面的else块的内容应该高一级。你格式化代码的方式,这绝对是你的意图,但你的IDE只是添加了一个不必要的else{}:-)只需注解掉两行,它应该工作:

if (Character.isLetter(c)) {
                        int shift = keyword.charAt(keywordIndex) - 'A';
                        if (mode.equals("D")) {
                            shift = 26 - shift;
                        }
                        // else {
                        c = (char)(((c + shift - 'A') % 26) + 'A');
                        keywordIndex = (keywordIndex + 1) % keyword.length();
                        c = Character.toUpperCase(c);
                        // }
                    }

相关问题