bytes[] getIV() 方法返回空值



我正在编写一个代码来加密和解密消息(使用 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);
    }
}

您不需要 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);
    }
}

相关内容

  • 没有找到相关文章

最新更新