我正在尝试使用证书生成密钥库以将其与JarSigner一起使用。这是我的代码:
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();
它可以工作,但是当我尝试使用此密钥库签署我的JAR时,我收到以下错误:
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.
我发现必须有私钥,但我不知道如何将其添加到证书中。你能救我吗?
答案 0 :(得分:1)
这是您可以向新密钥库添加私钥的方法:
...
char[] password = "123".toCharArray();
ks.load(null, password);
PrivateKeyEntry entry = new PrivateKeyEntry(pair.getPrivate(),
new java.security.cert.Certificate[]{PKCertificate});
ks.setEntry("hive",entry , new KeyStore.PasswordProtection("123".toCharArray()));
fos = new FileOutputStream("hive-keystore.pkcs12");
ks.store(fos, password);
fos.close();
我用jarsigner尝试了它并没有给出任何错误,所以应该没问题。