use of org.bouncycastle.asn1.x500.X500NameBuilder in project Openfire by igniterealtime.
the class CertificateManager method createX509V3Certificate.
/**
* Creates an X509 version3 certificate.
*
* @param kp KeyPair that keeps the public and private keys for the new certificate.
* @param days time to live
* @param issuerBuilder IssuerDN builder
* @param subjectBuilder SubjectDN builder
* @param domain Domain of the server.
* @param signAlgoritm Signature algorithm. This can be either a name or an OID.
* @return X509 V3 Certificate
* @throws GeneralSecurityException
* @throws IOException
*/
public static synchronized X509Certificate createX509V3Certificate(KeyPair kp, int days, X500NameBuilder issuerBuilder, X500NameBuilder subjectBuilder, String domain, String signAlgoritm) throws GeneralSecurityException, IOException {
PublicKey pubKey = kp.getPublic();
PrivateKey privKey = kp.getPrivate();
byte[] serno = new byte[8];
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed((new Date().getTime()));
random.nextBytes(serno);
BigInteger serial = (new java.math.BigInteger(serno)).abs();
X500Name issuerDN = issuerBuilder.build();
X500Name subjectDN = subjectBuilder.build();
// builder
JcaX509v3CertificateBuilder certBuilder = new //
JcaX509v3CertificateBuilder(//
issuerDN, //
serial, //
new Date(), //
new Date(System.currentTimeMillis() + days * (1000L * 60 * 60 * 24)), //
subjectDN, //
pubKey);
// add subjectAlternativeName extension
boolean critical = subjectDN.getRDNs().length == 0;
ASN1Sequence othernameSequence = new DERSequence(new ASN1Encodable[] { new ASN1ObjectIdentifier("1.3.6.1.5.5.7.8.5"), new DERUTF8String(domain) });
GeneralName othernameGN = new GeneralName(GeneralName.otherName, othernameSequence);
GeneralNames subjectAltNames = new GeneralNames(new GeneralName[] { othernameGN });
certBuilder.addExtension(Extension.subjectAlternativeName, critical, subjectAltNames);
// add keyIdentifiers extensions
JcaX509ExtensionUtils utils = new JcaX509ExtensionUtils();
certBuilder.addExtension(Extension.subjectKeyIdentifier, false, utils.createSubjectKeyIdentifier(pubKey));
certBuilder.addExtension(Extension.authorityKeyIdentifier, false, utils.createAuthorityKeyIdentifier(pubKey));
try {
// build the certificate
ContentSigner signer = new JcaContentSignerBuilder(signAlgoritm).build(privKey);
X509CertificateHolder cert = certBuilder.build(signer);
// verify the validity
if (!cert.isValidOn(new Date())) {
throw new GeneralSecurityException("Certificate validity not valid");
}
// verify the signature (self-signed)
ContentVerifierProvider verifierProvider = new JcaContentVerifierProviderBuilder().build(pubKey);
if (!cert.isSignatureValid(verifierProvider)) {
throw new GeneralSecurityException("Certificate signature not valid");
}
return new JcaX509CertificateConverter().getCertificate(cert);
} catch (OperatorCreationException | CertException e) {
throw new GeneralSecurityException(e);
}
}
use of org.bouncycastle.asn1.x500.X500NameBuilder in project zaproxy by zaproxy.
the class SslCertificateServiceImpl method createCertForHost.
@Override
public KeyStore createCertForHost(String hostname) throws NoSuchAlgorithmException, InvalidKeyException, CertificateException, NoSuchProviderException, SignatureException, KeyStoreException, IOException, UnrecoverableKeyException {
if (hostname == null) {
throw new IllegalArgumentException("Error, 'hostname' is not allowed to be null!");
}
if (this.caCert == null || this.caPrivKey == null || this.caPubKey == null) {
throw new MissingRootCertificateException(this.getClass() + " wasn't initialized! Got to options 'Dynamic SSL Certs' and create one.");
}
final KeyPair mykp = this.createKeyPair();
final PrivateKey privKey = mykp.getPrivate();
final PublicKey pubKey = mykp.getPublic();
X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE);
namebld.addRDN(BCStyle.CN, hostname);
namebld.addRDN(BCStyle.OU, "Zed Attack Proxy Project");
namebld.addRDN(BCStyle.O, "OWASP");
namebld.addRDN(BCStyle.C, "xx");
namebld.addRDN(BCStyle.EmailAddress, "owasp-zed-attack-proxy@lists.owasp.org");
X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(new X509CertificateHolder(caCert.getEncoded()).getSubject(), BigInteger.valueOf(serial.getAndIncrement()), new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30), new Date(System.currentTimeMillis() + 100 * (1000L * 60 * 60 * 24 * 30)), namebld.build(), pubKey);
certGen.addExtension(Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(pubKey.getEncoded()));
certGen.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));
certGen.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(new GeneralName(GeneralName.dNSName, hostname)));
ContentSigner sigGen;
try {
sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider("BC").build(caPrivKey);
} catch (OperatorCreationException e) {
throw new CertificateException(e);
}
final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen));
cert.checkValidity(new Date());
cert.verify(caPubKey);
final KeyStore ks = KeyStore.getInstance("JKS");
ks.load(null, null);
final Certificate[] chain = new Certificate[2];
chain[1] = this.caCert;
chain[0] = cert;
ks.setKeyEntry(ZAPROXY_JKS_ALIAS, privKey, PASSPHRASE, chain);
return ks;
}
use of org.bouncycastle.asn1.x500.X500NameBuilder in project XobotOS by xamarin.
the class IETFUtils method rDNsFromString.
public static RDN[] rDNsFromString(String name, X500NameStyle x500Style) {
X500NameTokenizer nTok = new X500NameTokenizer(name);
X500NameBuilder builder = new X500NameBuilder(x500Style);
while (nTok.hasMoreTokens()) {
String token = nTok.nextToken();
int index = token.indexOf('=');
if (index == -1) {
throw new IllegalArgumentException("badly formated directory string");
}
String attr = token.substring(0, index);
String value = token.substring(index + 1);
ASN1ObjectIdentifier oid = x500Style.attrNameToOID(attr);
if (value.indexOf('+') > 0) {
X500NameTokenizer vTok = new X500NameTokenizer(value, '+');
String v = vTok.nextToken();
Vector oids = new Vector();
Vector values = new Vector();
oids.addElement(oid);
values.addElement(v);
while (vTok.hasMoreTokens()) {
String sv = vTok.nextToken();
int ndx = sv.indexOf('=');
String nm = sv.substring(0, ndx);
String vl = sv.substring(ndx + 1);
oids.addElement(x500Style.attrNameToOID(nm));
values.addElement(vl);
}
builder.addMultiValuedRDN(toOIDArray(oids), toValueArray(values));
} else {
builder.addRDN(oid, value);
}
}
return builder.build().getRDNs();
}
use of org.bouncycastle.asn1.x500.X500NameBuilder in project drill by axbaretto.
the class WebServer method createHttpsConnector.
/**
* Create an HTTPS connector for given jetty server instance. If the admin has
* specified keystore/truststore settings they will be used else a self-signed
* certificate is generated and used.
* <p>
* This is a shameless copy of
* {@link org.apache.drill.exec.server.rest.Webserver#createHttpsConnector( )}.
* The two should be merged at some point. The primary issue is that the Drill
* version is tightly coupled to Drillbit configuration.
*
* @return Initialized {@link ServerConnector} for HTTPS connections.
* @throws Exception
*/
private ServerConnector createHttpsConnector(Config config) throws Exception {
LOG.info("Setting up HTTPS connector for web server");
final SslContextFactory sslContextFactory = new SslContextFactory();
// if (config.hasPath(ExecConstants.HTTP_KEYSTORE_PATH) &&
// !Strings.isNullOrEmpty(config.getString(ExecConstants.HTTP_KEYSTORE_PATH)))
// {
// LOG.info("Using configured SSL settings for web server");
// sslContextFactory.setKeyStorePath(config.getString(ExecConstants.HTTP_KEYSTORE_PATH));
// sslContextFactory.setKeyStorePassword(config.getString(ExecConstants.HTTP_KEYSTORE_PASSWORD));
//
// // TrustStore and TrustStore password are optional
// if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PATH)) {
// sslContextFactory.setTrustStorePath(config.getString(ExecConstants.HTTP_TRUSTSTORE_PATH));
// if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PASSWORD)) {
// sslContextFactory.setTrustStorePassword(config.getString(ExecConstants.HTTP_TRUSTSTORE_PASSWORD));
// }
// }
// } else {
LOG.info("Using generated self-signed SSL settings for web server");
final SecureRandom random = new SecureRandom();
// Generate a private-public key pair
final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024, random);
final KeyPair keyPair = keyPairGenerator.generateKeyPair();
final DateTime now = DateTime.now();
// Create builder for certificate attributes
final X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE).addRDN(BCStyle.OU, "Apache Drill (auth-generated)").addRDN(BCStyle.O, "Apache Software Foundation (auto-generated)").addRDN(BCStyle.CN, "Drill AM");
final Date notBefore = now.minusMinutes(1).toDate();
final Date notAfter = now.plusYears(5).toDate();
final BigInteger serialNumber = new BigInteger(128, random);
// Create a certificate valid for 5years from now.
final X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(// attributes
nameBuilder.build(), serialNumber, notBefore, notAfter, nameBuilder.build(), keyPair.getPublic());
// Sign the certificate using the private key
final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(keyPair.getPrivate());
final X509Certificate certificate = new JcaX509CertificateConverter().getCertificate(certificateBuilder.build(contentSigner));
// Check the validity
certificate.checkValidity(now.toDate());
// Make sure the certificate is self-signed.
certificate.verify(certificate.getPublicKey());
// Generate a random password for keystore protection
final String keyStorePasswd = RandomStringUtils.random(20);
final KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(null, null);
keyStore.setKeyEntry("DrillAutoGeneratedCert", keyPair.getPrivate(), keyStorePasswd.toCharArray(), new java.security.cert.Certificate[] { certificate });
sslContextFactory.setKeyStore(keyStore);
sslContextFactory.setKeyStorePassword(keyStorePasswd);
// }
final HttpConfiguration httpsConfig = new HttpConfiguration();
httpsConfig.addCustomizer(new SecureRequestCustomizer());
// SSL Connector
final ServerConnector sslConnector = new ServerConnector(jettyServer, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(httpsConfig));
sslConnector.setPort(config.getInt(DrillOnYarnConfig.HTTP_PORT));
return sslConnector;
}
use of org.bouncycastle.asn1.x500.X500NameBuilder in project dcos-commons by mesosphere.
the class CertificateAuthorityClientTest method createCSR.
private byte[] createCSR() throws IOException, OperatorCreationException {
KeyPair keyPair = KEY_PAIR_GENERATOR.generateKeyPair();
X500Name name = new X500NameBuilder().addRDN(BCStyle.CN, "issuer").build();
ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();
extensionsGenerator.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature));
extensionsGenerator.addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth }));
GeneralNames subAtlNames = new GeneralNames(new GeneralName[] { new GeneralName(GeneralName.dNSName, "test.com"), new GeneralName(GeneralName.iPAddress, TEST_IP_ADDR) });
extensionsGenerator.addExtension(Extension.subjectAlternativeName, true, subAtlNames);
ContentSigner signer = new JcaContentSignerBuilder("SHA256withRSA").build(keyPair.getPrivate());
PKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(name, keyPair.getPublic()).addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extensionsGenerator.generate());
return PEMUtils.toPEM(csrBuilder.build(signer));
}
Aggregations