【问题标题】:How to fix my Encryption/Decryption code to go into a text file如何修复我的加密/解密代码以进入文本文件
【发布时间】:2018-05-09 21:56:33
【问题描述】:

每次我运行代码时,它都会说找不到解密的文本文件。它可以在没有我无法修改的代码的情况下工作(因为我的老师写道我们不能)但是有了它,它拒绝工作。我的老师不会帮助我,我班上没有其他人知道如何用密码课编码。我已经使用了 PrintWriter 类,以及几乎所有其他的东西。所以我不知道该怎么办。有人请帮我弄清楚如何使它工作。

package Crypto;

import java.util.Scanner;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.FileWriter;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

public class Crypto {

 public static void main(String[] args) throws IOException {
  try {
   String key = "B1LLYB0B"; 

   FileInputStream One = new FileInputStream("CryptoPlaintext.txt");
   FileOutputStream Two = new FileOutputStream("CryptoCiphertext.txt");
   encrypt(key, One, Two);
   Two.flush();
   Two.close();


   FileInputStream One2 = new FileInputStream("CryptoCiphertext.txt");
   FileOutputStream Two2 = new FileOutputStream("CryptoDeciphered.txt");
   Two2.write(key.getBytes());
   Two2.close();
   decrypt(key, One2, Two2);
  } catch (Throwable e) {
   e.printStackTrace();
  }
 }

 public static void encrypt(String key, InputStream is, OutputStream os) throws Throwable {
  encryptOrDecrypt(key, Cipher.ENCRYPT_MODE, is, os);
 }

 public static void decrypt(String key, InputStream is, OutputStream os) throws Throwable {
  encryptOrDecrypt(key, Cipher.DECRYPT_MODE, is, os);
 }

 public static void encryptOrDecrypt(String key, int mode, InputStream is, OutputStream os) throws Throwable {

  DESKeySpec dks = new DESKeySpec(key.getBytes());
  SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
  SecretKey desKey = skf.generateSecret(dks);
  Cipher cipher = Cipher.getInstance("DES"); 

  if (mode == Cipher.ENCRYPT_MODE) {
   cipher.init(Cipher.ENCRYPT_MODE, desKey);
   CipherInputStream cis = new CipherInputStream(is, cipher);
   doCopy(cis, os);
  } else if (mode == Cipher.DECRYPT_MODE) {
   cipher.init(Cipher.DECRYPT_MODE, desKey);
   CipherOutputStream cos = new CipherOutputStream(os, cipher);
   doCopy(is, cos);
  }
 }

 public static void doCopy(InputStream is, OutputStream os) throws IOException {
  byte[] bytes = new byte[64];
  int numBytes;
  while ((numBytes = is.read(bytes)) != -1) {
   os.write(bytes, 0, numBytes);
  }
  os.flush();
  os.close();
  is.close();





      // =============================== DO NOT MODIFY ANY CODE BELOW HERE ===============================

   // Compare the files

      System.out.println(compareFiles() ? "The files are identical!" : "The files are NOT identical.");

 }

 /**  
  *  Compares the Plaintext file with the Deciphered file.
  *
  *    @return  true if files match, false if they do not
  */

 public static boolean compareFiles() throws IOException
 {

       Scanner pt = new Scanner(new File("CryptoPlaintext.txt")); // Open the plaintext file
       Scanner dc = new Scanner(new File("CryptoDeciphered.txt"));  // Open the deciphered file

       // Read through the files and compare them record by record.
       // If any of the records do not match, the files are not identical.

       while(pt.hasNextLine() && dc.hasNextLine())
         if(!pt.nextLine().equals(dc.nextLine())) return false;

       // If we have any records left over, then the files are not identical.

       if(pt.hasNextLine() || dc.hasNextLine()) return false;

       // The files are identical.

       return true;

 }
}

【问题讨论】:

  • 不能修改的代码是什么意思?你写了什么代码,老师写了什么代码?
  • 下面写着“不要修改下面的任何代码”的代码是我老师做的代码,他说不要乱用。其他的都是我的。
  • 你需要发布它给出的错误
  • "java.io.FileNotFoundException: CryptoDeciphered.txt (The system cannot find the file specified)" 这个错误我知道是什么意思但是不知道怎么解决。跨度>
  • 但这在逻辑上是错误的 - doCopy 是从 encrypt 调用的,它会查找仅在解密时写入的解密文件。除非您在没有 compareFiles 调用的情况下创建 doCopy 的副本,否则您无法解决这个问题,这很蹩脚。我认为这里有帮助的是知道你正在接受什么测试。

标签: java encryption fileinputstream fileoutputstream


【解决方案1】:

为什么会出现错误: 您在您的复制方法中调用compareFiles 方法,调用该方法将明文文件的加密内容复制到密文文件。发生此调用时,包含解密密文的文件不存在,但 compareFiles 方法需要该文件,从而导致您的异常。

如何改进你的代码:

  • 你不需要声明Two2.write(key.getBytes())
  • 使用 try-with-resource 语句自动刷新和关闭您的流
  • 标准库提供了将数据从路径复制到流的方法,反之亦然。看看Files.copy(...) 或 Guava 的ByteStreams.copy(...)
  • 改变你的方法的throws 子句,throws Throwable 只是一个糟糕的设计来摆脱正确的异常处理,如果你正在努力处理InvalidKeyExceptionNoSuchAlgorithmException 等,当你创建你的密码和重新抛出例如IllegalArgumentException 或自定义异常

这是一个如何实现它的示例:

public class Crypto
{
    public static void main(String[] args)
    {
        byte[] key = "B1LLYB0B".getBytes(StandardCharsets.UTF_8);

        Path plaintext = Paths.get("CryptoPlaintext.txt");
        Path ciphertext = plaintext.resolveSibling("CryptoCiphertext.txt");
        Path decrypted = ciphertext.resolveSibling("CryptoDeciphered.txt");

        try
        {
            // Encrypt plaintext.
            try (OutputStream os = encrypt(key, Files.newOutputStream(ciphertext)))
            {
                Files.copy(plaintext, os);
            }

            // Decrypt ciphertext.
            try (InputStream is = decrypt(key, Files.newInputStream(ciphertext)))
            {
                Files.copy(is, decrypted);
            }

            // TODO Compare plaintext and decrypted ciphertext.
        }
        catch (IOException e)
        {
            e.printStackTrace(); // TODO Handle exception properly.
        }
    }

    private static OutputStream encrypt(byte[] key, OutputStream os)
    {
        return new CipherOutputStream(os, getCipherInstance(key, Cipher.ENCRYPT_MODE));
    }

    private static InputStream decrypt(byte[] key, InputStream is)
    {
        return new CipherInputStream(is, getCipherInstance(key, Cipher.DECRYPT_MODE));
    }

    private static Cipher getCipherInstance(byte[] key, int mode)
    {
        // TODO Implement and return the desired cipher.
    }
}

顺便说一句:你的老师没有在compareFiles() 中关闭他的扫描仪,导致资源泄漏。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-22
    • 2020-08-23
    • 1970-01-01
    • 2022-10-12
    • 2011-06-21
    • 1970-01-01
    相关资源
    最近更新 更多