Creating keystore for jarsigner programmatically
Posted
by
skayred
on Stack Overflow
See other posts from Stack Overflow
or by skayred
Published on 2013-06-30T16:18:47Z
Indexed on
2013/06/30
16:21 UTC
Read the original article
Hit count: 324
I'm trying to generate keystore with certificate to use it with JarSigner. Here is my code:
System.out.println("Keystore generation...");
Security.addProvider(new BouncyCastleProvider());
String domainName = "example.org";
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
keyGen.initialize(1024, random);
KeyPair pair = keyGen.generateKeyPair();
X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();
int serial = new SecureRandom().nextInt();
v3CertGen.setSerialNumber(BigInteger.valueOf(serial < 0 ? -1 * serial : serial));
v3CertGen.setIssuerDN(new X509Principal("CN=" + domainName + ", OU=None, O=None L=None, C=None"));
v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));
v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365*10)));
v3CertGen.setSubjectDN(new X509Principal("CN=" + domainName + ", OU=None, O=None L=None, C=None"));
v3CertGen.setPublicKey(pair.getPublic());
v3CertGen.setSignatureAlgorithm("MD5WithRSAEncryption");
X509Certificate PKCertificate = v3CertGen.generateX509Certificate(pair.getPrivate());
FileOutputStream fos = new FileOutputStream("/Users/dmitrysavchenko/testCert.cert");
fos.write(PKCertificate.getEncoded());
fos.close();
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
char[] password = "123".toCharArray();
ks.load(null, password);
ks.setCertificateEntry("hive", PKCertificate);
fos = new FileOutputStream("/Users/dmitrysavchenko/hive-keystore.pkcs12");
ks.store(fos, password);
fos.close();
It works, but when I'm trying to sign my JAR with this keystore, I get the following error:
jarsigner: Certificate chain not found for: hive. hive must reference a valid KeyStore key entry containing a private key and corresponding public key certificate chain.
I've discovered that there must be a private key, but I don't know how to add it to certificate. Can you help me?
© Stack Overflow or respective owner