Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create certificate pfx file in java?

I need to create certificate pfx file with password in java. I search in google and can create certificate "cer" file in http://www.java2s.com/Tutorial/Java/0490__Security/CreatingaSelfSignedVersion3Certificate.htm

I add code in main

FileOutputStream fos = null;
fos = new FileOutputStream("public.cer");
fos.write(cert.getEncoded());
fos.close();

this only work without password.

like image 768
ducngm.hn Avatar asked Jan 24 '26 04:01

ducngm.hn


1 Answers

Normally a .pfx or pkcs12 its a keystore to save a public, private key pairs. Besides if you use a RSA key pair with public certificate as in your link sample, normally this certificate must be issued by a certificate authority, anyway I suppose that you're making an attempt to save a selfsigned certificate, to do so you have to use java.security.KeyStore class not a FileOutputStream directly, I give you a sample:

import java.io.FileOutputStream;
import java.security.KeyStore;
import java.security.cert.X509Certificate;

....

X509Certificate cert = // your certificate...
// generate a keystore instance
KeyStore ks = KeyStore.getInstance("PKCS12");
// save your cert inside the keystore
ks.setCertificateEntry("YourCertAlias", cert);
// create the outputstream to store the keystore
FileOutputStream fos = new FileOutputStream("/your_path/keystore.pfx");
// store the keystore protected with password
ks.store(fos, "yourPassword".toCharArray());

....

As I said normally in the keystore you store the key pairs, normally using: setKeyEntry(String alias, byte[] key, Certificate[] chain) or setKeyEntry(String alias, Key key, char[] password, Certificate[] chain) however with the code above you can store a certificate in keystore protecting it with a password. For more info take a look at: java keystore api.

Hope this helps,

like image 95
albciff Avatar answered Jan 26 '26 22:01

albciff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!