0

I'm writing a code which will encrypt and decrypt the message(using DES algorithm), and both messages will be displayed in Dialog box. But when i run the code i got nullPointerException. And after debugging the code i realize the null data is getting stored 'iv'. Here is my code:-

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);
    }
}
pritam parab
  • 85
  • 2
  • 10
  • **Do not use DES for new work**, it is no longer considered secure and has been superceeded by AES (Advanced Encryption Standard) DES only has key size is only 56 bits which is not considered to be secure, AES supports key sizes of 128,192 and 256 bits. See [Security comparison of DES and AES](https://security.stackexchange.com/a/26181/5121). – zaph Oct 12 '17 at 16:40

1 Answers1

-1

You don't need IvParameterSpec for decrypt the key.

Working code:

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);

    }

}
Yogi
  • 1,805
  • 13
  • 24
  • Since the generated key is not returned it will be impossible to decrypt later. Also relying on defaults for mode and padding is implementation specific and should be explicitly provided. Finally DES should not be used for new code. – zaph Oct 12 '17 at 16:49