use of org.bouncycastle.operator.jcajce.JcaContentSignerBuilder in project indy by Commonjava.
the class CertUtils method generateX509Certificate.
/**
* Create a self-signed X.509 cert
*
* @param pair KeyPair generated for this request
* @param dn the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB"
* @param days how many days from now the cert is valid for
* @param algorithm the signing algorithm, eg "SHA256withRSA"
* @return X509Certificate newly generated certificate
*/
public static X509Certificate generateX509Certificate(KeyPair pair, String dn, int days, String algorithm) throws GeneralSecurityException, OperatorCreationException, IOException {
JcaX509CertificateConverter converter = new JcaX509CertificateConverter();
PrivateKey subPrivKey = pair.getPrivate();
PublicKey subPubKey = pair.getPublic();
ContentSigner contentSignerBuilder = new JcaContentSignerBuilder(algorithm).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(subPrivKey);
X500Name name = new X500Name(dn);
Date expires = new Date(System.currentTimeMillis() + (MILLIS_IN_DAY * days));
X509CertificateHolder holder = new X509v3CertificateBuilder(name, allocateSerialNumber(), new Date(), expires, name, SubjectPublicKeyInfo.getInstance(subPubKey.getEncoded())).build(contentSignerBuilder);
X509Certificate cert = converter.getCertificate(holder);
logger.debug("Created cert using CA private key:\n" + cert.toString());
return cert;
}
use of org.bouncycastle.operator.jcajce.JcaContentSignerBuilder in project indy by Commonjava.
the class CertUtils method createSignedCertificate.
/**
* Generate X509Certificate using objects from existing issuer and subject certificates.
* The generated certificate is signed by issuer PrivateKey.
* @param certificate
* @param issuerCertificate
* @param issuerPrivateKey
* @param isIntermediate
* @return
* @throws Exception
*/
public static X509Certificate createSignedCertificate(X509Certificate certificate, X509Certificate issuerCertificate, PrivateKey issuerPrivateKey, boolean isIntermediate) throws Exception {
String issuerSigAlg = issuerCertificate.getSigAlgName();
X500Principal principal = issuerCertificate.getIssuerX500Principal();
JcaX509CertificateConverter converter = new JcaX509CertificateConverter();
JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder(issuerSigAlg).setProvider(BouncyCastleProvider.PROVIDER_NAME);
JcaX509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(principal, certificate.getSerialNumber(), certificate.getNotBefore(), certificate.getNotAfter(), certificate.getSubjectX500Principal(), certificate.getPublicKey());
if (isIntermediate) {
v3CertGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(-1));
}
return converter.getCertificate(v3CertGen.build(contentSignerBuilder.build(issuerPrivateKey)));
}
use of org.bouncycastle.operator.jcajce.JcaContentSignerBuilder in project tomee by apache.
the class SslTomEETest method test.
@Test
public void test() throws Exception {
final File keystore = new File("target/keystore");
{
// generate keystore/trustore
if (keystore.exists()) {
Files.delete(keystore);
}
keystore.getParentFile().mkdirs();
try (final FileOutputStream fos = new FileOutputStream(keystore)) {
final KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA");
keyGenerator.initialize(1024);
final KeyPair pair = keyGenerator.generateKeyPair();
final boolean addBc = Security.getProvider("BC") == null;
if (addBc) {
Security.addProvider(new BouncyCastleProvider());
}
try {
final X509v1CertificateBuilder x509v1CertificateBuilder = new JcaX509v1CertificateBuilder(new X500Name("cn=serveralias"), BigInteger.valueOf(1), new Date(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1)), new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(1)), new X500Name("cn=serveralias"), pair.getPublic());
final X509CertificateHolder certHldr = x509v1CertificateBuilder.build(new JcaContentSignerBuilder("SHA1WithRSA").setProvider("BC").build(pair.getPrivate()));
final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHldr);
final KeyStore ks = KeyStore.getInstance("JKS");
ks.load(null, "changeit".toCharArray());
ks.setKeyEntry("serveralias", pair.getPrivate(), "changeit".toCharArray(), new Certificate[] { cert });
ks.store(fos, "changeit".toCharArray());
} finally {
if (addBc) {
Security.removeProvider("BC");
}
}
} catch (final Exception e) {
Assert.fail(e.getMessage());
}
}
final Configuration configuration = new Configuration();
configuration.setSsl(true);
configuration.setKeystoreFile(keystore.getAbsolutePath());
configuration.setKeystorePass("changeit");
configuration.setKeyAlias("serveralias");
final Container container = new Container();
container.setup(configuration);
container.start();
Connector[] connectors = container.getTomcat().getService().findConnectors();
for (Connector conn : connectors) {
if (conn.getPort() == 8443) {
Object propertyObject = conn.getProperty("keystoreFile");
assertNotNull(propertyObject);
assertEquals(keystore.getAbsolutePath(), propertyObject.toString());
}
}
try {
assertEquals(8443, ManagementFactory.getPlatformMBeanServer().getAttribute(new ObjectName("Tomcat:type=ProtocolHandler,port=8443"), "port"));
} finally {
container.stop();
}
// ensure it is not always started
configuration.setSsl(false);
container.setup(configuration);
container.start();
try {
assertFalse(ManagementFactory.getPlatformMBeanServer().isRegistered(new ObjectName("Tomcat:type=ProtocolHandler,port=8443")));
} finally {
container.close();
}
}
use of org.bouncycastle.operator.jcajce.JcaContentSignerBuilder in project zookeeper by apache.
the class QuorumSSLTest method buildEndEntityCert.
public X509Certificate buildEndEntityCert(KeyPair keyPair, X509Certificate caCert, PrivateKey caPrivateKey, String hostname, String ipAddress, String crlPath, Integer ocspPort) throws Exception {
X509CertificateHolder holder = new JcaX509CertificateHolder(caCert);
ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(caPrivateKey);
List<GeneralName> generalNames = new ArrayList<>();
if (hostname != null) {
generalNames.add(new GeneralName(GeneralName.dNSName, hostname));
}
if (ipAddress != null) {
generalNames.add(new GeneralName(GeneralName.iPAddress, ipAddress));
}
SubjectPublicKeyInfo entityKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(PublicKeyFactory.createKey(keyPair.getPublic().getEncoded()));
X509ExtensionUtils extensionUtils = new BcX509ExtensionUtils();
JcaX509v3CertificateBuilder jcaX509v3CertificateBuilder = new JcaX509v3CertificateBuilder(holder.getSubject(), new BigInteger(128, new Random()), certStartTime, certEndTime, new X500Name("CN=Test End Entity Certificate"), keyPair.getPublic());
X509v3CertificateBuilder certificateBuilder = jcaX509v3CertificateBuilder.addExtension(Extension.authorityKeyIdentifier, false, extensionUtils.createAuthorityKeyIdentifier(holder)).addExtension(Extension.subjectKeyIdentifier, false, extensionUtils.createSubjectKeyIdentifier(entityKeyInfo)).addExtension(Extension.basicConstraints, true, new BasicConstraints(false)).addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
if (!generalNames.isEmpty()) {
certificateBuilder.addExtension(Extension.subjectAlternativeName, true, new GeneralNames(generalNames.toArray(new GeneralName[] {})));
}
if (crlPath != null) {
DistributionPointName distPointOne = new DistributionPointName(new GeneralNames(new GeneralName(GeneralName.uniformResourceIdentifier, "file://" + crlPath)));
certificateBuilder.addExtension(Extension.cRLDistributionPoints, false, new CRLDistPoint(new DistributionPoint[] { new DistributionPoint(distPointOne, null, null) }));
}
if (ocspPort != null) {
certificateBuilder.addExtension(Extension.authorityInfoAccess, false, new AuthorityInformationAccess(X509ObjectIdentifiers.ocspAccessMethod, new GeneralName(GeneralName.uniformResourceIdentifier, "http://" + hostname + ":" + ocspPort)));
}
return new JcaX509CertificateConverter().getCertificate(certificateBuilder.build(signer));
}
use of org.bouncycastle.operator.jcajce.JcaContentSignerBuilder in project zookeeper by apache.
the class QuorumSSLTest method setup.
@BeforeEach
public void setup() throws Exception {
quorumX509Util = new QuorumX509Util();
ClientBase.setupTestEnv();
tmpDir = createTmpDir().getAbsolutePath();
clientPortQp1 = PortAssignment.unique();
clientPortQp2 = PortAssignment.unique();
clientPortQp3 = PortAssignment.unique();
validKeystorePath = tmpDir + "/valid.jks";
truststorePath = tmpDir + "/truststore.jks";
quorumConfiguration = generateQuorumConfiguration();
Security.addProvider(new BouncyCastleProvider());
certStartTime = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(certStartTime);
cal.add(Calendar.YEAR, 1);
certEndTime = cal.getTime();
rootKeyPair = createKeyPair();
contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(rootKeyPair.getPrivate());
rootCertificate = createSelfSignedCertifcate(rootKeyPair);
// Write the truststore
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, PASSWORD);
trustStore.setCertificateEntry(rootCertificate.getSubjectDN().toString(), rootCertificate);
FileOutputStream outputStream = new FileOutputStream(truststorePath);
trustStore.store(outputStream, PASSWORD);
outputStream.flush();
outputStream.close();
defaultKeyPair = createKeyPair();
X509Certificate validCertificate = buildEndEntityCert(defaultKeyPair, rootCertificate, rootKeyPair.getPrivate(), HOSTNAME, "127.0.0.1", null, null);
writeKeystore(validCertificate, defaultKeyPair, validKeystorePath);
setSSLSystemProperties();
}
Aggregations