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 issuerCommonName Issuer CN string
* @param subjectCommonName Subject CN string
* @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, String issuerCommonName, String subjectCommonName, String domain, String signAlgoritm) throws GeneralSecurityException, IOException {
// subjectDN
X500NameBuilder subjectBuilder = new X500NameBuilder();
subjectBuilder.addRDN(BCStyle.CN, subjectCommonName);
// issuerDN
X500NameBuilder issuerBuilder = new X500NameBuilder();
issuerBuilder.addRDN(BCStyle.CN, issuerCommonName);
return createX509V3Certificate(kp, days, issuerBuilder, subjectBuilder, domain, signAlgoritm);
}
use of org.bouncycastle.asn1.x500.X500NameBuilder in project helios by spotify.
the class X509CertificateFactory method generate.
private CertificateAndPrivateKey generate(final AgentProxy agentProxy, final Identity identity, final String username) {
final UUID uuid = new UUID();
final Calendar calendar = Calendar.getInstance();
final X500Name issuerdn = new X500Name("C=US,O=Spotify,CN=helios-client");
final X500Name subjectdn = new X500NameBuilder().addRDN(BCStyle.UID, username).build();
calendar.add(Calendar.MILLISECOND, -validBeforeMilliseconds);
final Date notBefore = calendar.getTime();
calendar.add(Calendar.MILLISECOND, validBeforeMilliseconds + validAfterMilliseconds);
final Date notAfter = calendar.getTime();
// Reuse the UUID time as a SN
final BigInteger serialNumber = BigInteger.valueOf(uuid.getTime()).abs();
try {
final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
keyPairGenerator.initialize(KEY_SIZE, new SecureRandom());
final KeyPair keyPair = keyPairGenerator.generateKeyPair();
final SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(ASN1Sequence.getInstance(keyPair.getPublic().getEncoded()));
final X509v3CertificateBuilder builder = new X509v3CertificateBuilder(issuerdn, serialNumber, notBefore, notAfter, subjectdn, subjectPublicKeyInfo);
final DigestCalculator digestCalculator = new BcDigestCalculatorProvider().get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));
final X509ExtensionUtils utils = new X509ExtensionUtils(digestCalculator);
final SubjectKeyIdentifier keyId = utils.createSubjectKeyIdentifier(subjectPublicKeyInfo);
final String keyIdHex = KEY_ID_ENCODING.encode(keyId.getKeyIdentifier());
log.info("generating an X509 certificate for {} with key ID={} and identity={}", username, keyIdHex, identity.getComment());
builder.addExtension(Extension.subjectKeyIdentifier, false, keyId);
builder.addExtension(Extension.authorityKeyIdentifier, false, utils.createAuthorityKeyIdentifier(subjectPublicKeyInfo));
builder.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign));
builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(false));
final X509CertificateHolder holder = builder.build(new SshAgentContentSigner(agentProxy, identity));
final X509Certificate certificate = CERTIFICATE_CONVERTER.getCertificate(holder);
log.debug("generated certificate:\n{}", asPemString(certificate));
return new CertificateAndPrivateKey(certificate, keyPair.getPrivate());
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
use of org.bouncycastle.asn1.x500.X500NameBuilder in project robovm by robovm.
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();
if (token.indexOf('+') > 0) {
X500NameTokenizer pTok = new X500NameTokenizer(token, '+');
X500NameTokenizer vTok = new X500NameTokenizer(pTok.nextToken(), '=');
String attr = vTok.nextToken();
if (!vTok.hasMoreTokens()) {
throw new IllegalArgumentException("badly formatted directory string");
}
String value = vTok.nextToken();
ASN1ObjectIdentifier oid = x500Style.attrNameToOID(attr.trim());
if (pTok.hasMoreTokens()) {
Vector oids = new Vector();
Vector values = new Vector();
oids.addElement(oid);
values.addElement(unescape(value));
while (pTok.hasMoreTokens()) {
vTok = new X500NameTokenizer(pTok.nextToken(), '=');
attr = vTok.nextToken();
if (!vTok.hasMoreTokens()) {
throw new IllegalArgumentException("badly formatted directory string");
}
value = vTok.nextToken();
oid = x500Style.attrNameToOID(attr.trim());
oids.addElement(oid);
values.addElement(unescape(value));
}
builder.addMultiValuedRDN(toOIDArray(oids), toValueArray(values));
} else {
builder.addRDN(oid, unescape(value));
}
} else {
X500NameTokenizer vTok = new X500NameTokenizer(token, '=');
String attr = vTok.nextToken();
if (!vTok.hasMoreTokens()) {
throw new IllegalArgumentException("badly formatted directory string");
}
String value = vTok.nextToken();
ASN1ObjectIdentifier oid = x500Style.attrNameToOID(attr.trim());
builder.addRDN(oid, unescape(value));
}
}
return builder.build().getRDNs();
}
use of org.bouncycastle.asn1.x500.X500NameBuilder in project drill by apache.
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.
*
* @return Initialized {@link ServerConnector} for HTTPS connectios.
* @throws Exception
*/
private ServerConnector createHttpsConnector() throws Exception {
logger.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))) {
logger.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 {
logger.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, workManager.getContext().getEndpoint().getAddress());
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(embeddedJetty, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(httpsConfig));
sslConnector.setPort(config.getInt(ExecConstants.HTTP_PORT));
return sslConnector;
}
use of org.bouncycastle.asn1.x500.X500NameBuilder in project bnd by bndtools.
the class Server method createSelfSignedCertifcate.
private X509Certificate[] createSelfSignedCertifcate(KeyPair keyPair) throws Exception {
X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
nameBuilder.addRDN(BCStyle.CN, "localhost");
Date notBefore = new Date();
Date notAfter = new Date(System.currentTimeMillis() + 24 * 3 * 60 * 60 * 1000);
BigInteger serialNumber = new BigInteger(128, random);
X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(nameBuilder.build(), serialNumber, notBefore, notAfter, nameBuilder.build(), keyPair.getPublic());
ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(keyPair.getPrivate());
X509Certificate certificate = new JcaX509CertificateConverter().getCertificate(certificateBuilder.build(contentSigner));
return new X509Certificate[] { certificate };
}
Aggregations