Java - KeyPairGenerator.Initialize(int,SecureRandom) NullPointerException

3k Views Asked by At

I am creating a cryptographically-secure IM application in Java. The first step (after establishing a connection) is to exchange a public key (RSA-4096) so that the other party can create a symmetric key (AES-256), encrypt it with the other party's public key, send it over the connection, where the original party can decrypt the symmetric key with their private key and then both parties can exchange messages that are encrypted with the 256-bit key.

My problem is showing up at initializing the KeyPairGenerator, every time I call kpg.initialize(4096,sr) where kpg is the KeyPairGenerator's variable's name, and sr is the SecureRandom I have created, the program crashes and returns a NullPointerException, here is the full code:

CryptoBox.java:

    package crypto;

    import java.security.*;

    public class CryptoBox {
       private static SecureRandom sr = new SecureRandom();
       private static KeyPairGenerator kpg;
       private static KeyPair kp;

       private static Key PubKey;
       private static Key PrivKey;

       @SuppressWarnings("static-access")
       public void init(int keySize){
          try {
               sr.getInstance("SHA1PRNG");
               kpg.getInstance("RSA");
          } catch (NoSuchAlgorithmException e1) {
               // TODO Auto-generated catch block
               e1.printStackTrace();
          }
          try {
               kpg.initialize(keySize,sr); // <-- NullPointerException  
          }catch(Exception e){
               e.printStackTrace();
        return;
          }

          kp = kpg.genKeyPair();
          PubKey = kp.getPublic();
          PrivKey = kp.getPrivate();
       }

    }

Main.java:

package main;

import crypto.CryptoBox;

public class Main {

/**
 * @param args
 */
public static void main(String[] args){
    // TODO Auto-generated method stub
    CryptoBox cb = new CryptoBox();
    cb.init(4096); // <-- NullPointerException
}

}

the full error message is:

java.lang.NullPointerException
at crypto.CryptoBox.init(CryptoBox.java:23)
at main.Main.main(Main.java:15)
2

There are 2 best solutions below

2
On BEST ANSWER

Change sr.getInstance("SHA1PRNG"); to sr = KeyPairGenerator.getInstance("SHA1PRNG");

The copmiler probably already told you your mistake, but you choose to ignore it. Do yourself a favor and remove @SuppressWarnings("static-access"), too, that's what compiler errors are good for ;D

1
On

Having separate keys for each direction of message traffic is the cryptographically preferred pattern. So don't share a single symmetric key - but rather have each side generate their own, encrypt it with the other party's public key and send it as the first outgoing message then use the one they generated for encrypting messages they send and the one they received to decrypt each incoming message they receive.