我需要一些帮助。

在显示“您的代码已生成”的部分之后,请继续获取空指针异常。当我运行代码时,我不知道为什么。

在我将asHex类添加到同一程序包的新java文件中之前,它工作正常,但是现在即使删除了asHex,它也无法正常工作。

谁能帮我吗?

码:

public class myDesCbc2 {

public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException, IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {


        JFrame frame = null;
        JFileChooser fChoose = new JFileChooser(System.getProperty("user.home"));
        int returnVal = fChoose.showOpenDialog(frame);
        File myFile = fChoose.getSelectedFile();

        FileInputStream fis = new FileInputStream(myFile);
        BufferedReader stream = new BufferedReader(new InputStreamReader(fis, "ISO-8859-1"));
        String file;
        while ((file = stream.readLine()) != null) {

            JOptionPane.showOptionDialog(
                    null, "Generating a 56-bit DES key...", "Processing...", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, new Object[]{}, null);

        }
        // Create an 8-byte initialization vector
        SecureRandom sr = new SecureRandom();
        byte[] iv = new byte[8];
        sr.nextBytes(iv);
        IvParameterSpec IV = new IvParameterSpec(iv);

        // Create a 56-bit DES key
        KeyGenerator kg = KeyGenerator.getInstance("DES");

        // Initialize with keysize
        kg.init(56);
        Key mykey = kg.generateKey();

        JOptionPane.showOptionDialog(
                null, "Your key has been generated!", "Processing...", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, new Object[]{}, null);

        // Create a cipher object and use the generated key to initialize it
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

        cipher.init(Cipher.ENCRYPT_MODE, mykey, IV);

        byte[] plaintext = file.getBytes("UTF8");

        // Encrypt the text
        byte[] ciphertext = cipher.doFinal(plaintext);

        JOptionPane.showMessageDialog(
                null, "Your ciphertext is" + asHex(ciphertext), "Done!", JOptionPane.PLAIN_MESSAGE);

    }
}


asHex代码:

public class asHex {
      public static String asHex (byte buf[]) {
         StringBuffer strbuf = new StringBuffer(buf.length * 2);
         int i;

           for (i = 0; i < buf.length; i++) {
              if (((int) buf[i] & 0xff) < 0x10)
                strbuf.append("0");

                strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
              }

           return strbuf.toString();
  }

}

最佳答案

将代码放在while循环之后的while循环中,可以解决此问题。否则,当执行while循环之后的代码导致错误时,该文件为null。

07-24 13:45