I am trying to reproduce the output of "openssl dhparam -out dh1024.pem 1024" command programatically in Java. The code snippet is following:-
DHParametersGenerator generator = new DHParametersGenerator();
generator.init(1024, 0, new SecureRandom());
DHParameters params = generator.generateParameters();
// Generator G is set as random in params, but it has to be 2 to conform to openssl
DHParameters realParams = new DHParameters(params.getP(), BigInteger.valueOf(2));
byte[] p = realParams.getP().toByteArray();
byte[] g = realParams.getG().toByteArray();
byte[] l = new byte[(byte) realParams.getL()];
byte[] pgl = new byte[p.length+g.length+l.length];
System.arraycopy(p, 0, pgl, 0, p.length);
System.arraycopy(g, 0, pgl, p.length, g.length);
System.arraycopy(l, 0, pgl, p.length+g.length, l.length);
So basically I am concatenating the values of P,G and L parameters in a byte array "pgl" and then saving it in a file using the PEMWriter class from BC. But when I try to use it via openssl, I get the following error:-
Cannot load DH parameters from /etc/openvpn/easy-rsa/keys/dh1024.pem: error:0D07207B:asn1 encoding routines:ASN1_get_object:header too long: error:0D068066:asn1 encoding routines:ASN1_CHECK_TLEN:bad object header: error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error: error:0906700D:PEM routines:PEM_ASN1_read_bio:ASN1 lib
.... which leads me to believe that I am encoding the DH Parameters wrongly, but I cannot find anywhere the correct way to encode this. Can anyone help me in this? I've been bouncing my head against the castle wall fro many days now but to no avail .... please help :(