简单加密程序故障

时间:2015-01-18 01:51:11

标签: java encryption

我的加密程序应该使用两个字符的密钥(16位,每个字符8位)来加密和解密文本文件。加密和解密的公式由相同的公式给出:

Encrypted(M) = M ^ (K||K||...)
and
Decrypted(M) = M ^ (K||K||...)

其中M是文本文件的内容,^是独占的,而K是密钥。密钥是连接的,直到它与文本文件内容的大小相同。

下面的encrypt()方法似乎有效,但是当我尝试使用decrypt()方法时,一些单词出来很好,但大多数都是乱码。除了一些变量命名之外,这两种方法是相同的。我真的很感激有关错误的一些反馈。

  public static void encrypt() throws IOException {
    String path = System.console().readLine("Enter the file to encrypt: ");
    String baseKey = System.console().readLine("\nEnter two characters for the key: ");

    FileReader file_to_read = new FileReader(path);
    BufferedReader buffReader = new BufferedReader(file_to_read);

    String preCrypt = ""; // preCrypt is the file, read as a string, before        encyption.
    String line = "";

    while ((line = buffReader.readLine()) != null) {
      preCrypt = preCrypt + line;
    }

    buffReader.close();

    int numOfBytes = preCrypt.length();

    // If the number of bytes in the file is odd, add a space to the end.
    if(numOfBytes % 2 != 0) {
      preCrypt = preCrypt + " ";
      numOfBytes++;
}

    // Adjust the key so that it is the same length as the file.
    String key = baseKey;
     while (key.length() != numOfBytes)
    {
      key = key + baseKey;
    }

    StringBuilder decrypted = new StringBuilder();
    for(int i = 0; i < numOfBytes; i++) // Perform the encryption.
    {
      decrypted.append((char)(preCrypt.charAt(i) ^ key.charAt(i)));
    }

    PrintWriter out = new PrintWriter(path); // Write changes to file.
    out.println(decrypted.toString());
    out.close();
    }

  public static void decrypt() throws IOException {
    String path = System.console().readLine("Enter the file to decrypt: ");
    String baseKey = System.console().readLine("\nEnter two characters for the key: ");

    FileReader file_to_read = new FileReader(path);
    BufferedReader buffReader = new BufferedReader(file_to_read);

    String preCrypt = ""; // preCrypt is the file, read as a string, before decyption.
    String line = "";

    while ((line = buffReader.readLine()) != null) {
     preCrypt = preCrypt + line;
   }

    buffReader.close();

    int numOfBytes = preCrypt.length();

    // If the number of bytes in the file is odd, add a space to the end.
    if(numOfBytes % 2 != 0) {
      preCrypt = preCrypt + " ";
      numOfBytes++;
    }

    // Adjust the key so that it is the same length as the file.
    String key = baseKey;
    while (key.length() != numOfBytes)
    {
      key = key + baseKey;
    }

    StringBuilder encrypted = new StringBuilder();
    for(int i = 0; i < numOfBytes; i++)// Perform the decryption.
    {
      encrypted.append((char)(preCrypt.charAt(i) ^ key.charAt(i)));
    }

    PrintWriter out = new PrintWriter(path); // Write changes to the file.
    out.println(encrypted.toString());
    out.close();
  }

0 个答案:

没有答案