Search in sources :

Example 11 with X500NameBuilder

use of org.spongycastle.asn1.x500.X500NameBuilder in project gitblit by gitblit.

the class X509Utils method buildDistinguishedName.

/**
	 * Builds a distinguished name from the X509Metadata.
	 *
	 * @return a DN
	 */
private static X500Name buildDistinguishedName(X509Metadata metadata) {
    X500NameBuilder dnBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    setOID(dnBuilder, metadata, "C", null);
    setOID(dnBuilder, metadata, "ST", null);
    setOID(dnBuilder, metadata, "L", null);
    setOID(dnBuilder, metadata, "O", Constants.NAME);
    setOID(dnBuilder, metadata, "OU", Constants.NAME);
    setOID(dnBuilder, metadata, "E", metadata.emailAddress);
    setOID(dnBuilder, metadata, "CN", metadata.commonName);
    X500Name dn = dnBuilder.build();
    return dn;
}
Also used : X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder) X500Name(org.bouncycastle.asn1.x500.X500Name)

Example 12 with X500NameBuilder

use of org.spongycastle.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);
    }
}
Also used : BcDigestCalculatorProvider(org.bouncycastle.operator.bc.BcDigestCalculatorProvider) KeyPair(java.security.KeyPair) X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder) Calendar(java.util.Calendar) DigestCalculator(org.bouncycastle.operator.DigestCalculator) SecureRandom(java.security.SecureRandom) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) X500Name(org.bouncycastle.asn1.x500.X500Name) KeyPairGenerator(java.security.KeyPairGenerator) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) UUID(com.eaio.uuid.UUID) X509ExtensionUtils(org.bouncycastle.cert.X509ExtensionUtils) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Example 13 with X500NameBuilder

use of org.spongycastle.asn1.x500.X500NameBuilder in project zaproxy by zaproxy.

the class SslCertificateUtils method createRootCA.

/**
	 * Creates a new Root CA certificate and returns private and public key as
	 * {@link KeyStore}. The {@link KeyStore#getDefaultType()} is used.
	 *
	 * @return
	 * @throws NoSuchAlgorithmException If no providers are found
	 * for 'RSA' key pair generator
	 * or 'SHA1PRNG' Secure random number generator
	 * @throws IllegalStateException in case of errors during assembling {@link KeyStore}
	 */
public static final KeyStore createRootCA() throws NoSuchAlgorithmException {
    final Date startDate = Calendar.getInstance().getTime();
    final Date expireDate = new Date(startDate.getTime() + (DEFAULT_VALID_DAYS * 24L * 60L * 60L * 1000L));
    final KeyPairGenerator g = KeyPairGenerator.getInstance("RSA");
    g.initialize(2048, SecureRandom.getInstance("SHA1PRNG"));
    final KeyPair keypair = g.genKeyPair();
    final PrivateKey privKey = keypair.getPrivate();
    final PublicKey pubKey = keypair.getPublic();
    Security.addProvider(new BouncyCastleProvider());
    Random rnd = new Random();
    // using the hash code of the user's name and home path, keeps anonymity
    // but also gives user a chance to distinguish between each other
    X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE);
    namebld.addRDN(BCStyle.CN, "OWASP Zed Attack Proxy Root CA");
    namebld.addRDN(BCStyle.L, Integer.toHexString(System.getProperty("user.name").hashCode()) + Integer.toHexString(System.getProperty("user.home").hashCode()));
    namebld.addRDN(BCStyle.O, "OWASP Root CA");
    namebld.addRDN(BCStyle.OU, "OWASP ZAP Root CA");
    namebld.addRDN(BCStyle.C, "xx");
    X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(namebld.build(), BigInteger.valueOf(rnd.nextInt()), startDate, expireDate, namebld.build(), pubKey);
    KeyStore ks = null;
    try {
        certGen.addExtension(Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(pubKey.getEncoded()));
        certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
        certGen.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.cRLSign));
        KeyPurposeId[] eku = { KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth, KeyPurposeId.anyExtendedKeyUsage };
        certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(eku));
        final ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider("BC").build(privKey);
        final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen));
        ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null, null);
        ks.setKeyEntry(SslCertificateService.ZAPROXY_JKS_ALIAS, privKey, SslCertificateService.PASSPHRASE, new Certificate[] { cert });
    } catch (final Exception e) {
        throw new IllegalStateException("Errors during assembling root CA.", e);
    }
    return ks;
}
Also used : KeyPair(java.security.KeyPair) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder) KeyPurposeId(org.bouncycastle.asn1.x509.KeyPurposeId) PublicKey(java.security.PublicKey) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) KeyPairGenerator(java.security.KeyPairGenerator) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) KeyStore(java.security.KeyStore) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Random(java.util.Random) SecureRandom(java.security.SecureRandom) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 14 with X500NameBuilder

use of org.spongycastle.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();
}
Also used : X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder) ASN1String(org.bouncycastle.asn1.ASN1String) DERUniversalString(org.bouncycastle.asn1.DERUniversalString) Vector(java.util.Vector) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 15 with X500NameBuilder

use of org.spongycastle.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;
}
Also used : KeyPair(java.security.KeyPair) X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) KeyPairGenerator(java.security.KeyPairGenerator) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) KeyStore(java.security.KeyStore) DateTime(org.joda.time.DateTime) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) ServerConnector(org.eclipse.jetty.server.ServerConnector) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) BigInteger(java.math.BigInteger)

Aggregations

X500NameBuilder (org.bouncycastle.asn1.x500.X500NameBuilder)13 Date (java.util.Date)10 X509Certificate (java.security.cert.X509Certificate)8 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)7 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)7 ContentSigner (org.bouncycastle.operator.ContentSigner)7 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)7 BigInteger (java.math.BigInteger)6 KeyPair (java.security.KeyPair)6 X500Name (org.bouncycastle.asn1.x500.X500Name)6 JcaX509v3CertificateBuilder (org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder)6 KeyPairGenerator (java.security.KeyPairGenerator)5 PrivateKey (java.security.PrivateKey)5 SecureRandom (java.security.SecureRandom)5 CertificateException (java.security.cert.CertificateException)5 IOException (java.io.IOException)4 PublicKey (java.security.PublicKey)4 GeneralSecurityException (java.security.GeneralSecurityException)3 KeyStore (java.security.KeyStore)3 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)3