org.bouncycastle.asn1.x500.style.BCStyle Java Examples

The following examples show how to use org.bouncycastle.asn1.x500.style.BCStyle. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LdapAuthenticator.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
private Set<String> rolesFromDN(String userDN) throws LDAPException, GeneralSecurityException {
  SearchRequest searchRequest = new SearchRequest(config.getRoleBaseDN(),
      SearchScope.SUB, Filter.createEqualityFilter("uniqueMember", userDN));
  Set<String> roles = Sets.newLinkedHashSet();

  LDAPConnection connection = connectionFactory.getLDAPConnection();
  try {
    SearchResult sr = connection.search(searchRequest);

    for (SearchResultEntry sre : sr.getSearchEntries()) {
      X500Name x500Name = new X500Name(sre.getDN());
      RDN[] rdns = x500Name.getRDNs(BCStyle.CN);
      if (rdns.length == 0) {
        logger.error("Could not create X500 Name for role:" + sre.getDN());
      } else {
        String commonName = IETFUtils.valueToString(rdns[0].getFirst().getValue());
        roles.add(commonName);
      }
    }
  } finally {
    connection.close();
  }

  return roles;
}
 
Example #2
Source File: CertificateNamesGenerator.java    From dcos-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a Subject for service certificate.
 */
public X500Name getSubject() {
  // Create subject CN as pod-name-0-task-name.service-name
  String cn = String.format("%s.%s",
      EndpointUtils.removeSlashes(EndpointUtils.replaceDotsWithDashes(taskInstanceName)),
      EndpointUtils.removeSlashes(EndpointUtils.replaceDotsWithDashes(serviceName)));

  if (cn.length() > CN_MAX_LENGTH) {
    cn = cn.substring(cn.length() - CN_MAX_LENGTH);
  }

  return new X500NameBuilder()
      .addRDN(BCStyle.CN, cn)
      .addRDN(BCStyle.O, "Mesosphere, Inc")
      .addRDN(BCStyle.L, "San Francisco")
      .addRDN(BCStyle.ST, "CA")
      .addRDN(BCStyle.C, "US")
      .build();
}
 
Example #3
Source File: KeyGenerator.java    From chvote-1-0 with GNU Affero General Public License v3.0 6 votes vote down vote up
private X509v3CertificateBuilder createCertificateBuilder(KeyPair keyPair) throws PropertyConfigurationException, CertIOException {
    X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    nameBuilder.addRDN(BCStyle.CN, propertyConfigurationService.getConfigValue(CERT_COMMON_NAME_PROPERTY));
    nameBuilder.addRDN(BCStyle.O, propertyConfigurationService.getConfigValue(CERT_ORGANISATION_PROPERTY));
    nameBuilder.addRDN(BCStyle.OU, propertyConfigurationService.getConfigValue(CERT_ORGANISATIONAL_UNIT_PROPERTY));
    nameBuilder.addRDN(BCStyle.C, propertyConfigurationService.getConfigValue(CERT_COUNTRY_PROPERTY));
    X500Name x500Name = nameBuilder.build();

    BigInteger serial = new BigInteger(CERT_SERIAL_NUMBER_BIT_SIZE, SecureRandomFactory.createPRNG());

    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());

    Date startDate = new Date();
    Date endDate = Date.from(startDate.toInstant().plus(propertyConfigurationService.getConfigValueAsInt(CERT_VALIDITY_DAYS_PROPERTY), ChronoUnit.DAYS));

    X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(x500Name, serial, startDate, endDate, x500Name, publicKeyInfo);

    String certFriendlyName = propertyConfigurationService.getConfigValue(CERT_PRIVATE_FRIENDLY_NAME_PROPERTY);
    certificateBuilder.addExtension(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, false, new DERBMPString(certFriendlyName));
    return certificateBuilder;
}
 
Example #4
Source File: CertificateNamesGeneratorTest.java    From dcos-commons with Apache License 2.0 6 votes vote down vote up
@Test
public void testSlashesInServiceName() throws Exception {
    String serviceNameWithSlashes = "service/name/with/slashes";
    String serviceNameWithoutSlashes = "servicenamewithslashes";

    CertificateNamesGenerator certificateNamesGenerator =
            new CertificateNamesGenerator(serviceNameWithSlashes, mockTaskSpec, mockPodInstance, SCHEDULER_CONFIG);

    Assert.assertEquals(String.format("%s-%s.%s", POD_NAME, TestConstants.TASK_NAME, serviceNameWithoutSlashes),
            certificateNamesGenerator.getSubject().getRDNs(BCStyle.CN)[0].getFirst().getValue().toString());

    List<String> names = Arrays.stream(certificateNamesGenerator.getSANs().getNames())
            .map(name -> name.getName().toString())
            .collect(Collectors.toList());
    Assert.assertEquals(1, names.size());
    Assert.assertTrue(names.toString(), names.contains(taskDnsName(TestConstants.TASK_NAME, serviceNameWithoutSlashes)));
    Assert.assertFalse(names.contains(taskDnsName("*", serviceNameWithoutSlashes)));
    Assert.assertFalse(names.contains(taskVipName("*", serviceNameWithoutSlashes)));

    Assert.assertEquals(
            toSansHash("some-pod-test-task-name.servicenamewithslashes." + SCHEDULER_CONFIG.getAutoipTLD()),
            certificateNamesGenerator.getSANsHash());
}
 
Example #5
Source File: ZTSClientTest.java    From athenz with Apache License 2.0 6 votes vote down vote up
@Test
public void testGenerateInstanceRefreshRequestSubDomain() {

    File privkey = new File("./src/test/resources/unit_test_private_k0.pem");
    PrivateKey privateKey = Crypto.loadPrivateKey(privkey);

    InstanceRefreshRequest req = ZTSClient.generateInstanceRefreshRequest("coretech.system",
            "test", privateKey, "aws", 3600);
    assertNotNull(req);

    PKCS10CertificationRequest certReq = Crypto.getPKCS10CertRequest(req.getCsr());
    assertEquals("coretech.system.test", Crypto.extractX509CSRCommonName(certReq));

    X500Name x500name = certReq.getSubject();
    RDN cnRdn = x500name.getRDNs(BCStyle.CN)[0];
    assertEquals("coretech.system.test", IETFUtils.valueToString(cnRdn.getFirst().getValue()));
    assertEquals("test.coretech-system.aws.athenz.cloud", Crypto.extractX509CSRDnsNames(certReq).get(0));
}
 
Example #6
Source File: NameUtil.java    From portecle with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gets the common name from the given X500Name.
 *
 * @param name the X.500 name
 * @return the common name, null if not found
 */
public static String getCommonName(X500Name name)
{
	if (name == null)
	{
		return null;
	}

	RDN[] rdns = name.getRDNs(BCStyle.CN);
	if (rdns.length == 0)
	{
		return null;
	}

	return rdns[0].getFirst().getValue().toString();
}
 
Example #7
Source File: CertificateManager.java    From Launcher with GNU General Public License v3.0 6 votes vote down vote up
public void generateCA() throws NoSuchAlgorithmException, IOException, OperatorCreationException, InvalidAlgorithmParameterException {
    ECGenParameterSpec ecGenSpec = new ECGenParameterSpec("secp384k1");
    KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
    generator.initialize(ecGenSpec, SecurityHelper.newRandom());
    KeyPair pair = generator.generateKeyPair();
    LocalDateTime startDate = LocalDate.now().atStartOfDay();

    X500NameBuilder subject = new X500NameBuilder();
    subject.addRDN(BCStyle.CN, orgName.concat(" CA"));
    subject.addRDN(BCStyle.O, orgName);

    X509v3CertificateBuilder builder = new X509v3CertificateBuilder(
            subject.build(),
            new BigInteger("0"),
            Date.from(startDate.atZone(ZoneId.systemDefault()).toInstant()),
            Date.from(startDate.plusDays(3650).atZone(ZoneId.systemDefault()).toInstant()),
            new X500Name("CN=ca"),
            SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded()));
    JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256WITHECDSA");
    ContentSigner signer = csBuilder.build(pair.getPrivate());
    ca = builder.build(signer);
    caKey = PrivateKeyFactory.createKey(pair.getPrivate().getEncoded());
}
 
Example #8
Source File: CertificateManager.java    From Launcher with GNU General Public License v3.0 6 votes vote down vote up
public X509CertificateHolder generateCertificate(String subjectName, PublicKey subjectPublicKey) throws OperatorCreationException {
    SubjectPublicKeyInfo subjectPubKeyInfo = SubjectPublicKeyInfo.getInstance(subjectPublicKey.getEncoded());
    BigInteger serial = BigInteger.valueOf(SecurityHelper.newRandom().nextLong());
    Date startDate = Date.from(Instant.now().minus(minusHours, ChronoUnit.HOURS));
    Date endDate = Date.from(startDate.toInstant().plus(validDays, ChronoUnit.DAYS));

    X500NameBuilder subject = new X500NameBuilder();
    subject.addRDN(BCStyle.CN, subjectName);
    subject.addRDN(BCStyle.O, orgName);
    X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(ca.getSubject(), serial,
            startDate, endDate, subject.build(), subjectPubKeyInfo);

    AlgorithmIdentifier sigAlgId = ca.getSignatureAlgorithm();
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    ContentSigner sigGen = new BcECContentSignerBuilder(sigAlgId, digAlgId).build(caKey);

    return v3CertGen.build(sigGen);
}
 
Example #9
Source File: CommonUtil.java    From gmhelper with Apache License 2.0 6 votes vote down vote up
/**
 * 如果不知道怎么填充names,可以查看org.bouncycastle.asn1.x500.style.BCStyle这个类,
 * names的key值必须是BCStyle.DefaultLookUp中存在的(可以不关心大小写)
 *
 * @param names
 * @return
 * @throws InvalidX500NameException
 */
public static X500Name buildX500Name(Map<String, String> names) throws InvalidX500NameException {
    if (names == null || names.size() == 0) {
        throw new InvalidX500NameException("names can not be empty");
    }
    try {
        X500NameBuilder builder = new X500NameBuilder();
        Iterator itr = names.entrySet().iterator();
        BCStyle x500NameStyle = (BCStyle) BCStyle.INSTANCE;
        Map.Entry entry;
        while (itr.hasNext()) {
            entry = (Map.Entry) itr.next();
            ASN1ObjectIdentifier oid = x500NameStyle.attrNameToOID((String) entry.getKey());
            builder.addRDN(oid, (String) entry.getValue());
        }
        return builder.build();
    } catch (Exception ex) {
        throw new InvalidX500NameException(ex.getMessage(), ex);
    }
}
 
Example #10
Source File: TestDefaultProfile.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * Generates an CSR with the extension specified.
 * This function is used to get an Invalid CSR and test that PKI profile
 * rejects these invalid extensions, Hence the function name, by itself it
 * is a well formed CSR, but our PKI profile will treat it as invalid CSR.
 *
 * @param kPair - Key Pair.
 * @return CSR  - PKCS10CertificationRequest
 * @throws OperatorCreationException - on Error.
 */
private PKCS10CertificationRequest getInvalidCSR(KeyPair kPair,
    Extensions extensions) throws OperatorCreationException {
  X500NameBuilder namebuilder =
      new X500NameBuilder(X500Name.getDefaultStyle());
  namebuilder.addRDN(BCStyle.CN, "invalidCert");
  PKCS10CertificationRequestBuilder p10Builder =
      new JcaPKCS10CertificationRequestBuilder(namebuilder.build(),
          keyPair.getPublic());
  p10Builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest,
      extensions);
  JcaContentSignerBuilder csBuilder =
      new JcaContentSignerBuilder(this.securityConfig.getSignatureAlgo());
  ContentSigner signer = csBuilder.build(keyPair.getPrivate());
  return p10Builder.build(signer);
}
 
Example #11
Source File: AbstractX509CertificateService.java    From flashback with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected X500Name getSubject(String commonName) {
  X500NameBuilder x500NameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
  x500NameBuilder.addRDN(BCStyle.CN, commonName);
  x500NameBuilder.addRDN(BCStyle.O, _certificateAuthority.getOrganization());
  x500NameBuilder.addRDN(BCStyle.OU, _certificateAuthority.getOrganizationalUnit());
  return x500NameBuilder.build();
}
 
Example #12
Source File: CertificateNamesGeneratorTest.java    From dcos-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetSubjectWithLongCN() throws Exception {
    Mockito.when(mockTaskSpec.getName()).thenReturn(UUID.randomUUID().toString());
    CertificateNamesGenerator certificateNamesGenerator =
            new CertificateNamesGenerator(UUID.randomUUID().toString(), mockTaskSpec, mockPodInstance, SCHEDULER_CONFIG);
    RDN[] cnRDNs = certificateNamesGenerator.getSubject().getRDNs(BCStyle.CN);
    Assert.assertEquals(cnRDNs.length, 1);
    Assert.assertEquals(64, cnRDNs[0].getFirst().getValue().toString().length());
}
 
Example #13
Source File: CertificateNamesGeneratorTest.java    From dcos-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetSubject() throws Exception {
    CertificateNamesGenerator certificateNamesGenerator =
            new CertificateNamesGenerator(TestConstants.SERVICE_NAME, mockTaskSpec, mockPodInstance, SCHEDULER_CONFIG);
    RDN[] cnRDNs = certificateNamesGenerator.getSubject().getRDNs(BCStyle.CN);
    Assert.assertEquals(cnRDNs.length, 1);
    Assert.assertEquals(String.format("%s-%s.%s", POD_NAME, TestConstants.TASK_NAME, TestConstants.SERVICE_NAME),
            cnRDNs[0].getFirst().getValue().toString());
}
 
Example #14
Source File: Crypto.java    From athenz with Apache License 2.0 5 votes vote down vote up
public static String extractX509CertCommonName(X509Certificate x509Cert) {

        // in case there are multiple CNs, we're only looking at the first one
        // in Athenz we should never have multiple CNs so we're going to reject
        // any certificate that has multiple values

        return extractX509CertSubjectField(x509Cert, BCStyle.CN);
    }
 
Example #15
Source File: Crypto.java    From athenz with Apache License 2.0 5 votes vote down vote up
public static String extractX509CertSubjectOField(X509Certificate x509Cert) {

        // in case there are multiple Os, we're only looking at the first one
        // in Athenz we should never have multiple Os so we're going to reject
        // any certificate that has multiple values

        return extractX509CertSubjectField(x509Cert, BCStyle.O);
    }
 
Example #16
Source File: X500NameUtils.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Return CN of a X.500 name
 *
 * @param name X.500 name object
 * @return CN from Name or an empty string if no CN found
 */
public static String extractCN(X500Name name) {
	for (RDN rdn : name.getRDNs()) {
		AttributeTypeAndValue atav = rdn.getFirst();

		if (atav.getType().equals(BCStyle.CN)) {
			return atav.getValue().toString();
		}
	}

	return "";
}
 
Example #17
Source File: X500NameUtils.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates an X500Name object from the given components.
 *
 * @param commonName
 * @param organisationUnit
 * @param organisationName
 * @param localityName
 * @param stateName
 * @param countryCode
 * @param emailAddress
 * @return X500Name object from the given components
 */
public static X500Name buildX500Name(String commonName, String organisationUnit, String organisationName,
		String localityName, String stateName, String countryCode, String emailAddress) {

	X500NameBuilder x500NameBuilder = new X500NameBuilder(KseX500NameStyle.INSTANCE);

	if (emailAddress != null) {
		x500NameBuilder.addRDN(BCStyle.E, emailAddress);
	}
	if (countryCode != null) {
		x500NameBuilder.addRDN(BCStyle.C, countryCode);
	}
	if (stateName != null) {
		x500NameBuilder.addRDN(BCStyle.ST, stateName);
	}
	if (localityName != null) {
		x500NameBuilder.addRDN(BCStyle.L, localityName);
	}
	if (organisationName != null) {
		x500NameBuilder.addRDN(BCStyle.O, organisationName);
	}
	if (organisationUnit != null) {
		x500NameBuilder.addRDN(BCStyle.OU, organisationUnit);
	}
	if (commonName != null) {
		x500NameBuilder.addRDN(BCStyle.CN, commonName);
	}

	return x500NameBuilder.build();
}
 
Example #18
Source File: SpkacSubject.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Construct SpkacSubject.
 *
 * @param name
 *            Name
 */
public SpkacSubject(X500Name name) {
	cn = getRdn(name, BCStyle.CN);
	ou = getRdn(name, BCStyle.OU);
	o = getRdn(name, BCStyle.O);
	l = getRdn(name, BCStyle.L);
	st = getRdn(name, BCStyle.ST);
	c = getRdn(name, BCStyle.C);
}
 
Example #19
Source File: CompositeConditionTest.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testAtLeastOne() {
	CompositeCondition condition = new CompositeCondition(Assert.AT_LEAST_ONE);
	condition.addChild(new CertSubjectDNAttributeCondition(Arrays.asList(BCStyle.C.toString())));

	LOG.info(condition.toString());
	assertTrue(condition.check(certificate));

	condition.addChild(new CertSubjectDNAttributeCondition(Arrays.asList(BCStyle.EmailAddress.toString())));
	LOG.info(condition.toString());
	assertTrue(condition.check(certificate));
}
 
Example #20
Source File: DDistinguishedNameChooser.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
private void okPressed() {
	if (editable) {

		X500Name dn = distinguishedNameChooser.getDN();

		if (dn == null) {
			return;
		}

		if (dn.toString().isEmpty()) {
			JOptionPane.showMessageDialog(this,
					res.getString("DDistinguishedNameChooser.ValueReqAtLeastOneField.message"), getTitle(),
					JOptionPane.WARNING_MESSAGE);
			return;
		}

		for (RDN rdn : dn.getRDNs(BCStyle.C)) {
			String countryCode = rdn.getFirst().getValue().toString();
			if ((countryCode != null) && (countryCode.length() != 2)) {
				JOptionPane.showMessageDialog(this,
						res.getString("DDistinguishedNameChooser.CountryCodeTwoChars.message"), getTitle(),
						JOptionPane.WARNING_MESSAGE);
				return;
			}
		}

		distinguishedName = dn;
	}

	closeDialog();
}
 
Example #21
Source File: Crypto.java    From athenz with Apache License 2.0 5 votes vote down vote up
public static String extractX509CSRSubjectOField(PKCS10CertificationRequest certReq) {

        // in case there are multiple Os, we're only looking at the first one
        // in Athenz we should never have multiple Os so we're going to reject
        // any csr that has multiple values

        return extractX509CSRSubjectField(certReq, BCStyle.O);
    }
 
Example #22
Source File: ClientFingerprintTrustManager.java    From cava with Apache License 2.0 5 votes vote down vote up
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine)
    throws CertificateException {
  X509Certificate cert = chain[0];
  X500Name x500name = new JcaX509CertificateHolder(cert).getSubject();
  RDN cn = x500name.getRDNs(BCStyle.CN)[0];
  String hostname = IETFUtils.valueToString(cn.getFirst().getValue());
  checkTrusted(chain, hostname);
}
 
Example #23
Source File: ClientFingerprintTrustManager.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine)
    throws CertificateException {
  X509Certificate cert = chain[0];
  X500Name x500name = new JcaX509CertificateHolder(cert).getSubject();
  RDN cn = x500name.getRDNs(BCStyle.CN)[0];
  String hostname = IETFUtils.valueToString(cn.getFirst().getValue());
  checkTrusted(chain, hostname);
}
 
Example #24
Source File: CertificateHelper.java    From signer with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static KeyStore createServerCertificate(String commonName,
		SubjectAlternativeNameHolder subjectAlternativeNames, Authority authority, Certificate caCert,
		PrivateKey caPrivKey)
		throws NoSuchAlgorithmException, NoSuchProviderException, IOException, OperatorCreationException,
		CertificateException, InvalidKeyException, SignatureException, KeyStoreException {

	KeyPair keyPair = generateKeyPair(FAKE_KEYSIZE);

	X500Name issuer = new X509CertificateHolder(caCert.getEncoded()).getSubject();
	BigInteger serial = BigInteger.valueOf(initRandomSerial());

	X500NameBuilder name = new X500NameBuilder(BCStyle.INSTANCE);
	name.addRDN(BCStyle.CN, commonName);
	name.addRDN(BCStyle.O, authority.certOrganisation());
	name.addRDN(BCStyle.OU, authority.certOrganizationalUnitName());
	X500Name subject = name.build();

	X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuer, serial, NOT_BEFORE, NOT_AFTER,
			subject, keyPair.getPublic());

	builder.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(keyPair.getPublic()));
	builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));

	subjectAlternativeNames.fillInto(builder);

	X509Certificate cert = signCertificate(builder, caPrivKey);

	cert.checkValidity(new Date());
	cert.verify(caCert.getPublicKey());

	KeyStore result = KeyStore.getInstance("PKCS12"
	/* , PROVIDER_NAME */);
	result.load(null, null);
	Certificate[] chain = { cert, caCert };
	result.setKeyEntry(authority.alias(), keyPair.getPrivate(), authority.password(), chain);

	return result;
}
 
Example #25
Source File: CertificateHelper.java    From signer with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static KeyStore createRootCertificate(Authority authority, String keyStoreType)
		throws NoSuchAlgorithmException, NoSuchProviderException, CertIOException, IOException,
		OperatorCreationException, CertificateException, KeyStoreException {

	KeyPair keyPair = generateKeyPair(ROOT_KEYSIZE);

	X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
	nameBuilder.addRDN(BCStyle.CN, authority.commonName());
	nameBuilder.addRDN(BCStyle.O, authority.organization());
	nameBuilder.addRDN(BCStyle.OU, authority.organizationalUnitName());

	X500Name issuer = nameBuilder.build();
	BigInteger serial = BigInteger.valueOf(initRandomSerial());
	X500Name subject = issuer;
	PublicKey pubKey = keyPair.getPublic();

	X509v3CertificateBuilder generator = new JcaX509v3CertificateBuilder(issuer, serial, NOT_BEFORE, NOT_AFTER,
			subject, pubKey);

	generator.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(pubKey));
	generator.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));

	KeyUsage usage = new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment
			| KeyUsage.dataEncipherment | KeyUsage.cRLSign);
	generator.addExtension(Extension.keyUsage, false, usage);

	ASN1EncodableVector purposes = new ASN1EncodableVector();
	purposes.add(KeyPurposeId.id_kp_serverAuth);
	purposes.add(KeyPurposeId.id_kp_clientAuth);
	purposes.add(KeyPurposeId.anyExtendedKeyUsage);
	generator.addExtension(Extension.extendedKeyUsage, false, new DERSequence(purposes));

	X509Certificate cert = signCertificate(generator, keyPair.getPrivate());

	KeyStore result = KeyStore.getInstance(keyStoreType/* , PROVIDER_NAME */);
	result.load(null, null);
	result.setKeyEntry(authority.alias(), keyPair.getPrivate(), authority.password(), new Certificate[] { cert });
	return result;
}
 
Example #26
Source File: CompositeConditionTest.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testDefault() {
	CompositeCondition condition = new CompositeCondition();
	condition.addChild(new CertSubjectDNAttributeCondition(Arrays.asList(BCStyle.C.toString())));

	LOG.info(condition.toString());
	assertTrue(condition.check(certificate));

	condition.addChild(new CertSubjectDNAttributeCondition(Arrays.asList(BCStyle.EmailAddress.toString())));
	LOG.info(condition.toString());
	assertFalse(condition.check(certificate));
}
 
Example #27
Source File: TlsCertificateAuthorityClientSocketFactory.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized Socket connectSocket(int connectTimeout, Socket socket, HttpHost host, InetSocketAddress remoteAddress,
                                         InetSocketAddress localAddress, HttpContext context) throws IOException {
    Socket result = super.connectSocket(connectTimeout, socket, host, remoteAddress, localAddress, context);
    if (!SSLSocket.class.isInstance(result)) {
        throw new IOException("Expected tls socket");
    }
    SSLSocket sslSocket = (SSLSocket) result;
    java.security.cert.Certificate[] peerCertificateChain = sslSocket.getSession().getPeerCertificates();
    if (peerCertificateChain.length != 1) {
        throw new IOException("Expected root ca cert");
    }
    if (!X509Certificate.class.isInstance(peerCertificateChain[0])) {
        throw new IOException("Expected root ca cert in X509 format");
    }
    String cn;
    try {
        X509Certificate certificate = (X509Certificate) peerCertificateChain[0];
        cn = IETFUtils.valueToString(new JcaX509CertificateHolder(certificate).getSubject().getRDNs(BCStyle.CN)[0].getFirst().getValue());
        certificates.add(certificate);
    } catch (Exception e) {
        throw new IOException(e);
    }
    if (!caHostname.equals(cn)) {
        throw new IOException("Expected cn of " + caHostname + " but got " + cn);
    }
    return result;
}
 
Example #28
Source File: ClientAuthenticateMiddleware.java    From bouncr with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public HttpResponse handle(HttpRequest request, MiddlewareChain<HttpRequest, NRES, ?, ?> chain) {
    request = MixinUtils.mixin(request, PrincipalAvailable.class);
    String clientDN = request.getHeaders().get("X-Client-DN");
    if (!isAuthenticated(request) && clientDN != null) {
        RDN cn = new X500Name(clientDN).getRDNs(BCStyle.CN)[0];
        String account = IETFUtils.valueToString(cn.getFirst().getValue());

    }
    return castToHttpResponse(chain.next(request));
}
 
Example #29
Source File: CertificateUtils.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
private static Map<ASN1ObjectIdentifier, Integer> createDnOrderMap() {
    Map<ASN1ObjectIdentifier, Integer> orderMap = new HashMap<>();
    int count = 0;
    orderMap.put(BCStyle.CN, count++);
    orderMap.put(BCStyle.L, count++);
    orderMap.put(BCStyle.ST, count++);
    orderMap.put(BCStyle.O, count++);
    orderMap.put(BCStyle.OU, count++);
    orderMap.put(BCStyle.C, count++);
    orderMap.put(BCStyle.STREET, count++);
    orderMap.put(BCStyle.DC, count++);
    orderMap.put(BCStyle.UID, count++);
    return Collections.unmodifiableMap(orderMap);
}
 
Example #30
Source File: CertificateAutogenTask.java    From Launcher with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Path process(Path inputFile) throws IOException {
    if (signedDataGenerator != null) return inputFile;
    try {
        LogHelper.warning("You are using an auto-generated certificate (sign.enabled false). It is not good");
        LogHelper.warning("It is highly recommended that you use the correct certificate (sign.enabled true)");
        LogHelper.warning("You can use GenerateCertificateModule or your own certificate.");
        X500NameBuilder subject = new X500NameBuilder();
        subject.addRDN(BCStyle.CN, server.config.projectName.concat(" Autogenerated"));
        subject.addRDN(BCStyle.O, server.config.projectName);
        LocalDateTime startDate = LocalDate.now().atStartOfDay();
        X509v3CertificateBuilder builder = new X509v3CertificateBuilder(
                subject.build(),
                new BigInteger("0"),
                Date.from(startDate.atZone(ZoneId.systemDefault()).toInstant()),
                Date.from(startDate.plusDays(3650).atZone(ZoneId.systemDefault()).toInstant()),
                new X500Name("CN=ca"),
                SubjectPublicKeyInfo.getInstance(server.publicKey.getEncoded()));
        builder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeId.id_kp_codeSigning));
        //builder.addExtension(Extension.keyUsage, false, new KeyUsage(1));
        JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256WITHECDSA");
        ContentSigner signer = csBuilder.build(server.privateKey);
        bcCertificate = builder.build(signer);
        certificate = new JcaX509CertificateConverter().setProvider("BC")
                .getCertificate(bcCertificate);
        ArrayList<Certificate> chain = new ArrayList<>();
        chain.add(certificate);
        signedDataGenerator = SignHelper.createSignedDataGenerator(server.privateKey, certificate, chain, "SHA256WITHECDSA");
    } catch (OperatorCreationException | CMSException | CertificateException e) {
        LogHelper.error(e);
    }
    return inputFile;
}