我正在编写一个代码,用于加密和解密消息(使用DES算法),这两条消息都将显示在对话框中。但是当我运行代码时,我得到了nullPointerException。在调试代码后,我意识到空数据被存储为'iv'。 这是我的代码: -
import javax.crypto.spec.*;
import javax.crypto.*;
import javax.swing.*;
public class des
{
public static void main(String ar[]) throws Exception
{
KeyGenerator keygen=KeyGenerator.getInstance("DES");
SecretKey secretkey=keygen.generateKey();
Cipher cip=Cipher.getInstance("DES");
String inputText=JOptionPane.showInputDialog("Give input:");
byte[] iv=cip.getIV();
IvParameterSpec ps=new IvParameterSpec(iv);
cip.init(Cipher.ENCRYPT_MODE,secretkey);
byte[] encrypted=cip.doFinal(inputText.getBytes());
cip.init(Cipher.DECRYPT_MODE,secretkey,ps);
byte[] decrypted=cip.doFinal(encrypted);
JOptionPane.showMessageDialog(null,"Encrypted :"+new String(encrypted)+"\n Decrypted :"+new String(decrypted));
System.exit(0);
}
}
答案 0 :(得分:-1)
您不需要IvParameterSpec来解密密钥。
工作代码:
public class des {
public static void main(String[] args) throws Exception {
KeyGenerator keygen=KeyGenerator.getInstance("DES");
SecretKey secretkey=keygen.generateKey();
Cipher encrypter=Cipher.getInstance("DES");
Cipher decrypter=Cipher.getInstance("DES");
String inputText=JOptionPane.showInputDialog("Give input:");
encrypter.init(Cipher.ENCRYPT_MODE,secretkey);
byte[] encrypted=encrypter.doFinal(inputText.getBytes());
decrypter.init(Cipher.DECRYPT_MODE,secretkey);
byte[] decrypted=decrypter.doFinal(encrypted);
JOptionPane.showMessageDialog(null,"Encrypted :"+new String(encrypted)+"\n Decrypted :"+new String(decrypted));
System.exit(0);
}
}