0
我需要一些幫助。無法修復空指針異常
在聲明「您的代碼已生成」部分之後,請繼續收到空指針異常。當我運行我的代碼,我無法弄清楚爲什麼。
在將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();
}
}
請編輯您的帖子,並附上錯誤[stack trace](http://en.wikipedia.org/wiki/Stack_trace) – Christian
如果您想成爲一名優秀的程序員,您應該閱讀[Java命名約定](http: //www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367) – Baby
並標記引發異常的代碼行 –