Java Code Examples for org.bouncycastle.asn1.x509.GeneralNames

The following examples show how to use org.bouncycastle.asn1.x509.GeneralNames. These examples are extracted from open source projects. 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 Project: DeviceConnect-Android   Author: DeviceConnect   File: AbstractKeyStoreManager.java    License: MIT License 7 votes vote down vote up
private X509Certificate generateX509V3Certificate(final KeyPair keyPair,
                                                  final X500Principal subject,
                                                  final X500Principal issuer,
                                                  final Date notBefore,
                                                  final Date notAfter,
                                                  final BigInteger serialNumber,
                                                  final GeneralNames generalNames,
                                                  final boolean isCA) throws GeneralSecurityException {
    X509V3CertificateGenerator generator = new X509V3CertificateGenerator();
    generator.setSerialNumber(serialNumber);
    generator.setIssuerDN(issuer);
    generator.setSubjectDN(subject);
    generator.setNotBefore(notBefore);
    generator.setNotAfter(notAfter);
    generator.setPublicKey(keyPair.getPublic());
    generator.setSignatureAlgorithm("SHA256WithRSAEncryption");
    generator.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(isCA));
    generator.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(160));
    generator.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));
    if (generalNames != null) {
        generator.addExtension(X509Extensions.SubjectAlternativeName, false, generalNames);
    }
    return generator.generateX509Certificate(keyPair.getPrivate(), SecurityUtil.getSecurityProvider());
}
 
Example #2
Source Project: hadoop-ozone   Author: apache   File: DefaultProfile.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Validates the SubjectAlternative names in the Certificate.
 *
 * @param ext - Extension - SAN, which allows us to get the SAN names.
 * @param profile - This profile.
 * @return - True if the request contains only SANs, General names that we
 * support. False otherwise.
 */
private static Boolean validateSubjectAlternativeName(Extension ext,
    PKIProfile profile) {
  if (ext.isCritical()) {
    // SAN extensions should not be marked as critical under ozone profile.
    LOG.error("SAN extension marked as critical in the Extension. {}",
        GeneralNames.getInstance(ext.getParsedValue()).toString());
    return false;
  }
  GeneralNames generalNames = GeneralNames.getInstance(ext.getParsedValue());
  for (GeneralName name : generalNames.getNames()) {
    try {
      if (!profile.validateGeneralName(name.getTagNo(),
          name.getName().toString())) {
        return false;
      }
    } catch (UnknownHostException e) {
      LOG.error("IP address validation failed."
          + name.getName().toString(), e);
      return false;
    }
  }
  return true;
}
 
Example #3
Source Project: nifi   Author: apache   File: TlsHelper.java    License: Apache License 2.0 6 votes vote down vote up
public static Extensions createDomainAlternativeNamesExtensions(List<String> domainAlternativeNames, String requestedDn) throws IOException {
    List<GeneralName> namesList = new ArrayList<>();

    try {
        final String cn = IETFUtils.valueToString(new X500Name(requestedDn).getRDNs(BCStyle.CN)[0].getFirst().getValue());
        namesList.add(new GeneralName(GeneralName.dNSName, cn));
    } catch (Exception e) {
        throw new IOException("Failed to extract CN from request DN: " + requestedDn, e);
    }

    if (domainAlternativeNames != null) {
        for (String alternativeName : domainAlternativeNames) {
             namesList.add(new GeneralName(IPAddress.isValid(alternativeName) ? GeneralName.iPAddress : GeneralName.dNSName, alternativeName));
         }
    }

    GeneralNames subjectAltNames = new GeneralNames(namesList.toArray(new GeneralName[]{}));
    ExtensionsGenerator extGen = new ExtensionsGenerator();
    extGen.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
    return extGen.generate();
}
 
Example #4
Source Project: besu   Author: hyperledger   File: SelfSignedP12Certificate.java    License: Apache License 2.0 6 votes vote down vote up
private static GeneralNames getSubjectAlternativeNames() {
  final List<GeneralName> hostGeneralNames =
      sanHostNames.stream()
          .map(hostName -> new GeneralName(GeneralName.dNSName, hostName))
          .collect(Collectors.toList());
  final List<GeneralName> ipGeneralNames =
      sanIpAddresses.stream()
          .map(ipAddress -> new GeneralName(GeneralName.iPAddress, ipAddress))
          .collect(Collectors.toList());
  final GeneralName[] generalNames =
      Stream.of(hostGeneralNames, ipGeneralNames)
          .flatMap(Collection::stream)
          .toArray(GeneralName[]::new);

  return new GeneralNames(generalNames);
}
 
Example #5
Source Project: nifi   Author: apache   File: TlsHelperTest.java    License: Apache License 2.0 6 votes vote down vote up
private List<String> extractSanFromCsr(JcaPKCS10CertificationRequest csr) {
    List<String> sans = new ArrayList<>();
    Attribute[] certAttributes = csr.getAttributes();
    for (Attribute attribute : certAttributes) {
        if (attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
            Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0));
            GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
            GeneralName[] names = gns.getNames();
            for (GeneralName name : names) {
                logger.info("Type: " + name.getTagNo() + " | Name: " + name.getName());
                String title = "";
                if (name.getTagNo() == GeneralName.dNSName) {
                    title = "DNS";
                } else if (name.getTagNo() == GeneralName.iPAddress) {
                    title = "IP Address";
                    // name.toASN1Primitive();
                } else if (name.getTagNo() == GeneralName.otherName) {
                    title = "Other Name";
                }
                sans.add(title + ": " + name.getName());
            }
        }
    }

    return sans;
}
 
Example #6
Source Project: localization_nifi   Author: wangrenlei   File: TlsHelperTest.java    License: Apache License 2.0 6 votes vote down vote up
private List<String> extractSanFromCsr(JcaPKCS10CertificationRequest csr) {
    List<String> sans = new ArrayList<>();
    Attribute[] certAttributes = csr.getAttributes();
    for (Attribute attribute : certAttributes) {
        if (attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
            Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0));
            GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
            GeneralName[] names = gns.getNames();
            for (GeneralName name : names) {
                logger.info("Type: " + name.getTagNo() + " | Name: " + name.getName());
                String title = "";
                if (name.getTagNo() == GeneralName.dNSName) {
                    title = "DNS";
                } else if (name.getTagNo() == GeneralName.iPAddress) {
                    title = "IP Address";
                    // name.toASN1Primitive();
                } else if (name.getTagNo() == GeneralName.otherName) {
                    title = "Other Name";
                }
                sans.add(title + ": " + name.getName());
            }
        }
    }

    return sans;
}
 
Example #7
Source Project: SecuritySample   Author: Catherine22   File: CRLDistributionPointsImpl.java    License: Apache License 2.0 6 votes vote down vote up
public CRLDistributionPointsImpl(X509Certificate cert) throws CertificateException, IOException {
	URINames = new ArrayList<>();
	byte[] extVal = cert.getExtensionValue(Extension.cRLDistributionPoints.getId());
	if (extVal == null)
		return;
	CRLDistPoint crlDistPoint = CRLDistPoint.getInstance(X509ExtensionUtil.fromExtensionValue(extVal));
	DistributionPoint[] points = crlDistPoint.getDistributionPoints();
	for (DistributionPoint p : points) {
		GeneralNames tmp = p.getCRLIssuer();
		if (tmp != null) {
			GeneralName[] crlIssers = tmp.getNames();
			for (int i = 0; i < crlIssers.length; i++) {
				if (crlIssers[i].getTagNo() == GeneralName.uniformResourceIdentifier) {
					String issuerUrl = crlIssers[i].toString();
					URINames.add(issuerUrl);
				}
			}
		}
	}
}
 
Example #8
Source Project: portecle   Author: scop   File: X509Ext.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get a formatted string value for the supplied general names object.
 *
 * @param generalNames General names
 * @param linkClass
 * @return Formatted string
 * @throws IOException
 */
private String getGeneralNamesString(GeneralNames generalNames, LinkClass linkClass)
    throws IOException
{
	GeneralName[] names = generalNames.getNames();
	StringBuilder strBuff = new StringBuilder();
	strBuff.append("<ul>");
	for (GeneralName name : names)
	{
		strBuff.append("<li>");
		strBuff.append(getGeneralNameString(name, linkClass));
		strBuff.append("</li>");
	}
	strBuff.append("</ul>");
	return strBuff.toString();
}
 
Example #9
Source Project: qpid-broker-j   Author: apache   File: TlsResourceBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private static Extension createAlternateNamesExtension(final AlternativeName[] alternativeName)
        throws CertificateException
{
    try
    {
        final GeneralName[] generalNames = Arrays.stream(alternativeName)
                                                 .map(an -> new GeneralName(an.getType().ordinal(),
                                                                            an.getName()))
                                                 .toArray(GeneralName[]::new);
        return new Extension(Extension.subjectAlternativeName,
                             false,
                             new GeneralNames(generalNames).getEncoded());
    }
    catch (IOException e)
    {
        throw new CertificateException(e);
    }
}
 
Example #10
Source Project: signer   Author: demoiselle   File: SigningCertificate.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Attribute getValue() {
    try {
        X509Certificate cert = (X509Certificate) certificates[0];
        Digest digest = DigestFactory.getInstance().factoryDefault();
        digest.setAlgorithm(DigestAlgorithmEnum.SHA_1);
        byte[] hash = digest.digest(cert.getEncoded());
        X500Name dirName = new X500Name(cert.getSubjectDN().getName());
        GeneralName name = new GeneralName(dirName);
        GeneralNames issuer = new GeneralNames(name);
        ASN1Integer serial = new ASN1Integer(cert.getSerialNumber());
        IssuerSerial issuerSerial = new IssuerSerial(issuer, serial);
        ESSCertID essCertId = new ESSCertID(hash, issuerSerial);
        return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(new DERSequence(new ASN1Encodable[]{new DERSequence(essCertId), new DERSequence(DERNull.INSTANCE)})));

    } catch (CertificateEncodingException ex) {
        throw new SignerException(ex.getMessage());
    }
}
 
Example #11
Source Project: dcos-commons   Author: mesosphere   File: CertificateNamesGenerator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns additional Subject Alternative Names for service certificates.
 */
public GeneralNames getSANs() {
  List<GeneralName> generalNames = new ArrayList<>();
  generalNames.add(new GeneralName(GeneralName.dNSName, autoIpHostname));

  // Process VIP names, if any
  vipSpecs.stream()
      .map(vipSpec -> new GeneralName(
          GeneralName.dNSName,
          EndpointUtils.toVipHostname(
              serviceName,
              schedulerConfig,
              new EndpointUtils.VipInfo(vipSpec.getVipName(), (int) vipSpec.getPort()))))
      .forEach(generalNames::add);

  return new GeneralNames(generalNames.toArray(new GeneralName[0]));
}
 
Example #12
Source Project: dcos-commons   Author: mesosphere   File: CertificateNamesGeneratorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetSANs() throws Exception {
    CertificateNamesGenerator certificateNamesGenerator =
            new CertificateNamesGenerator(TestConstants.SERVICE_NAME, mockTaskSpec, mockPodInstance, SCHEDULER_CONFIG);

    GeneralNames sans = certificateNamesGenerator.getSANs();
    Assert.assertEquals(1, sans.getNames().length);

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

    Assert.assertEquals(
            toSansHash("some-pod-test-task-name.service-name." + SCHEDULER_CONFIG.getAutoipTLD()),
            certificateNamesGenerator.getSANsHash());
}
 
Example #13
Source Project: dcos-commons   Author: mesosphere   File: CertificateNamesGeneratorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDiscoveryNameAddedAsSan() {
    Mockito.when(mockTaskSpec.getDiscovery()).thenReturn(Optional.of(mockDiscoverySpec));
    Mockito.when(mockDiscoverySpec.getPrefix()).thenReturn(Optional.of("custom-name"));
    CertificateNamesGenerator certificateNamesGenerator =
            new CertificateNamesGenerator(TestConstants.SERVICE_NAME, mockTaskSpec, mockPodInstance, SCHEDULER_CONFIG);

    GeneralNames sans = certificateNamesGenerator.getSANs();
    Assert.assertEquals(1, sans.getNames().length);

    List<String> names = Arrays.stream(sans.getNames())
            .map(name -> name.getName().toString())
            .collect(Collectors.toList());
    Assert.assertEquals(1, names.size());
    Assert.assertTrue(names.toString(), names.contains(taskDnsName("custom", "name-0", TestConstants.SERVICE_NAME)));

    Assert.assertEquals(toSansHash("custom-name-0.service-name." + SCHEDULER_CONFIG.getAutoipTLD()), certificateNamesGenerator.getSANsHash());
}
 
Example #14
Source Project: dcos-commons   Author: mesosphere   File: CertificateNamesGeneratorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testVipsAddedAsSans() {
    Mockito.when(mockResourceSet.getResources()).thenReturn(Collections.singletonList(mockVIPSpec));
    Mockito.when(mockVIPSpec.getVipName()).thenReturn("test-vip");
    Mockito.when(mockVIPSpec.getPort()).thenReturn(8000L);
    CertificateNamesGenerator certificateNamesGenerator =
            new CertificateNamesGenerator(TestConstants.SERVICE_NAME, mockTaskSpec, mockPodInstance, SCHEDULER_CONFIG);

    GeneralNames sans = certificateNamesGenerator.getSANs();
    Assert.assertEquals(2, sans.getNames().length);

    List<String> names = Arrays.stream(sans.getNames())
            .map(name -> name.getName().toString())
            .collect(Collectors.toList());
    Assert.assertEquals(2, names.size());
    Assert.assertTrue(names.toString(), names.contains(taskDnsName(TestConstants.TASK_NAME, TestConstants.SERVICE_NAME)));
    Assert.assertTrue(names.contains(taskVipName("test-vip", TestConstants.SERVICE_NAME)));

    Assert.assertEquals(
            toSansHash(
                    "some-pod-test-task-name.service-name." + SCHEDULER_CONFIG.getAutoipTLD() + ";" +
                    "test-vip.service-name." + SCHEDULER_CONFIG.getVipTLD()),
            certificateNamesGenerator.getSANsHash());
}
 
Example #15
Source Project: athenz   Author: yahoo   File: Crypto.java    License: Apache License 2.0 6 votes vote down vote up
public static List<String> extractX509CSRIPAddresses(PKCS10CertificationRequest certReq) {

        List<String> ipAddresses = new ArrayList<>();
        Attribute[] attributes = certReq.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
        for (Attribute attribute : attributes) {
            for (ASN1Encodable value : attribute.getAttributeValues()) {
                Extensions extensions = Extensions.getInstance(value);
                GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
                ///CLOVER:OFF
                if (gns == null) {
                    continue;
                }
                ///CLOVER:ON
                for (GeneralName name : gns.getNames()) {
                    if (name.getTagNo() == GeneralName.iPAddress) {
                        try {
                            InetAddress addr = InetAddress.getByAddress(((DEROctetString) name.getName()).getOctets());
                            ipAddresses.add(addr.getHostAddress());
                        } catch (UnknownHostException ignored) {
                        }
                    }
                }
            }
        }
        return ipAddresses;
    }
 
Example #16
Source Project: credhub   Author: cloudfoundry-incubator   File: CertificateReaderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void givenASelfSignedCertificate_setsCertificateFieldsCorrectly() {
  final String distinguishedName =
    "L=Europa, OU=test-org-unit, CN=test-common-name, C=MilkyWay, ST=Jupiter, O=test-org";
  final GeneralNames generalNames = new GeneralNames(
    new GeneralName(GeneralName.dNSName, "SolarSystem"));

  final CertificateReader certificateReader = new CertificateReader(BIG_TEST_CERT);

  assertThat(certificateReader.getSubjectName().toString(), equalTo(distinguishedName));
  assertThat(certificateReader.getKeyLength(), equalTo(4096));
  assertThat(certificateReader.getAlternativeNames(), equalTo(generalNames));
  assertThat(asList(certificateReader.getExtendedKeyUsage().getUsages()),
    containsInAnyOrder(KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth));
  assertThat(certificateReader.getKeyUsage().hasUsages(KeyUsage.digitalSignature),
    equalTo(true));
  assertThat(certificateReader.getDurationDays(), equalTo(30));
  assertThat(certificateReader.isSelfSigned(), equalTo(false));
  assertThat(certificateReader.isCa(), equalTo(false));
}
 
Example #17
Source Project: credhub   Author: cloudfoundry-incubator   File: CertificateReaderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void returnsParametersCorrectly() {
  final String distinguishedName =
    "L=Europa, OU=test-org-unit, CN=test-common-name, C=MilkyWay, ST=Jupiter, O=test-org";
  final GeneralNames generalNames = new GeneralNames(
    new GeneralName(GeneralName.dNSName, "SolarSystem"));

  final CertificateReader certificateReader = new CertificateReader(BIG_TEST_CERT);

  assertThat(certificateReader.getAlternativeNames(), equalTo(generalNames));
  assertThat(asList(certificateReader.getExtendedKeyUsage().getUsages()),
    containsInAnyOrder(KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth));
  assertThat(certificateReader.getKeyUsage().hasUsages(KeyUsage.digitalSignature),
    equalTo(true));
  assertThat(certificateReader.getSubjectName().toString(), equalTo(distinguishedName));
}
 
Example #18
Source Project: keystore-explorer   Author: kaikramer   File: X509Ext.java    License: GNU General Public License v3.0 6 votes vote down vote up
private String getSubjectAlternativeNameStringValue(byte[] value) throws IOException {
	// @formatter:off

	/*
	 * SubjectAltName ::= GeneralNames
	 *
	 * GeneralNames ::= ASN1Sequence SIZE (1..MAX) OF GeneralName
	 */

	// @formatter:on

	StringBuilder sb = new StringBuilder();

	GeneralNames subjectAltName = GeneralNames.getInstance(value);

	for (GeneralName generalName : subjectAltName.getNames()) {
		sb.append(GeneralNameUtil.toString(generalName));
		sb.append(NEWLINE);
	}

	return sb.toString();
}
 
Example #19
Source Project: keystore-explorer   Author: kaikramer   File: X509Ext.java    License: GNU General Public License v3.0 6 votes vote down vote up
private String getCertificateIssuerStringValue(byte[] value) throws IOException {
	// @formatter:off

	/*
	 * certificateIssuer ::= GeneralNames
	 *
	 * GeneralNames ::= ASN1Sequence SIZE (1..MAX) OF GeneralName
	 */

	// @formatter:on

	StringBuilder sb = new StringBuilder();

	GeneralNames certificateIssuer = GeneralNames.getInstance(value);

	for (GeneralName generalName : certificateIssuer.getNames()) {
		sb.append(GeneralNameUtil.toString(generalName));
		sb.append(NEWLINE);
	}

	return sb.toString();
}
 
Example #20
Source Project: keystore-explorer   Author: kaikramer   File: DAuthorityKeyIdentifier.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void prepopulateWithAuthorityCertDetails(X500Name authorityCertName, BigInteger authorityCertSerialNumber) {
	if (authorityCertName != null) {
		try {
			GeneralName generalName = new GeneralName(GeneralName.directoryName, authorityCertName);
			GeneralNames generalNames = new GeneralNames(generalName);

			jgnAuthorityCertIssuer.setGeneralNames(generalNames);
		} catch (Exception e) {
			DError.displayError(this, e);
			return;
		}
	}

	if (authorityCertSerialNumber != null) {
		jtfAuthorityCertSerialNumber.setText("" + authorityCertSerialNumber.toString());
		jtfAuthorityCertSerialNumber.setCaretPosition(0);
	}
}
 
Example #21
Source Project: keystore-explorer   Author: kaikramer   File: DAuthorityKeyIdentifier.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void prepopulateWithValue(byte[] value) throws IOException {
	AuthorityKeyIdentifier authorityKeyIdentifier = AuthorityKeyIdentifier.getInstance(value);

	if (authorityKeyIdentifier.getKeyIdentifier() != null) {
		jkiKeyIdentifier.setKeyIdentifier(authorityKeyIdentifier.getKeyIdentifier());
	}

	GeneralNames authorityCertIssuer = authorityKeyIdentifier.getAuthorityCertIssuer();

	if (authorityCertIssuer != null) {
		jgnAuthorityCertIssuer.setGeneralNames(authorityCertIssuer);
	}

	BigInteger authorityCertSerialNumber = authorityKeyIdentifier.getAuthorityCertSerialNumber();

	if (authorityCertSerialNumber != null) {
		jtfAuthorityCertSerialNumber.setText("" + authorityCertSerialNumber.longValue());
		jtfAuthorityCertSerialNumber.setCaretPosition(0);
	}
}
 
Example #22
Source Project: keystore-explorer   Author: kaikramer   File: DSubjectAlternativeName.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void okPressed() {
	GeneralNames alternativeName = jgnAlternativeName.getGeneralNames();

	if (alternativeName.getNames().length == 0) {
		JOptionPane.showMessageDialog(this, res.getString("DSubjectAlternativeName.ValueReq.message"), getTitle(),
				JOptionPane.WARNING_MESSAGE);
		return;
	}

	try {
		value = alternativeName.getEncoded(ASN1Encoding.DER);
	} catch (IOException e) {
		DError.displayError(this, e);
		return;
	}

	closeDialog();
}
 
Example #23
Source Project: DeviceConnect-Android   Author: DeviceConnect   File: EndPointKeyStoreManager.java    License: MIT License 6 votes vote down vote up
/**
 * 証明書署名要求のオブジェクトを作成する.
 *
 * @param keyPair キーペア
 * @param commonName コモンネーム
 * @param generalNames SANs
 * @return 証明書署名要求のオブジェクト
 * @throws GeneralSecurityException 作成に失敗した場合
 */
private static PKCS10CertificationRequest createCSR(final KeyPair keyPair,
                                                    final String commonName,
                                                    final GeneralNames generalNames) throws GeneralSecurityException {
    final String signatureAlgorithm = "SHA256WithRSAEncryption";
    final X500Principal principal = new X500Principal("CN=" + commonName + ", O=Device Connect Project, L=N/A, ST=N/A, C=JP");
    DERSequence sanExtension= new DERSequence(new ASN1Encodable[] {
            X509Extensions.SubjectAlternativeName,
            new DEROctetString(generalNames)
    });
    DERSet extensions = new DERSet(new DERSequence(sanExtension));
    DERSequence extensionRequest = new DERSequence(new ASN1Encodable[] {
            PKCSObjectIdentifiers.pkcs_9_at_extensionRequest,
            extensions
    });
    DERSet attributes = new DERSet(extensionRequest);
    return new PKCS10CertificationRequest(
            signatureAlgorithm,
            principal,
            keyPair.getPublic(),
            attributes,
            keyPair.getPrivate(),
            SecurityUtil.getSecurityProvider());
}
 
Example #24
Source Project: Openfire   Author: igniterealtime   File: CertificateManager.java    License: Apache License 2.0 6 votes vote down vote up
protected static GeneralNames getSubjectAlternativeNames( Set<String> sanDnsNames )
{
    final ASN1EncodableVector subjectAlternativeNames = new ASN1EncodableVector();
    if ( sanDnsNames != null )
    {
        for ( final String dnsNameValue : sanDnsNames )
        {
            subjectAlternativeNames.add(
                new GeneralName( GeneralName.dNSName, dnsNameValue )
            );
        }
    }

    return GeneralNames.getInstance(
        new DERSequence( subjectAlternativeNames )
    );
}
 
Example #25
Source Project: Spark   Author: igniterealtime   File: SparkTrustManager.java    License: Apache License 2.0 5 votes vote down vote up
public Collection<X509CRL> loadCRL(X509Certificate[] chain) throws IOException, InvalidAlgorithmParameterException,
        NoSuchAlgorithmException, CertStoreException, CRLException, CertificateException {

    // for each certificate in chain
    for (X509Certificate cert : chain) {
        if (cert.getExtensionValue(Extension.cRLDistributionPoints.getId()) != null) {
            ASN1Primitive primitive = JcaX509ExtensionUtils
                    .parseExtensionValue(cert.getExtensionValue(Extension.cRLDistributionPoints.getId()));
            // extract distribution point extension
            CRLDistPoint distPoint = CRLDistPoint.getInstance(primitive);
            DistributionPoint[] dp = distPoint.getDistributionPoints();
            // each distribution point extension can hold number of distribution points
            for (DistributionPoint d : dp) {
                DistributionPointName dpName = d.getDistributionPoint();
                // Look for URIs in fullName
                if (dpName != null && dpName.getType() == DistributionPointName.FULL_NAME) {
                    GeneralName[] genNames = GeneralNames.getInstance(dpName.getName()).getNames();
                    // Look for an URI
                    for (GeneralName genName : genNames) {
                        // extract url
                        URL url = new URL(genName.getName().toString());
                        try {
                            // download from Internet to the collection
                            crlCollection.add(downloadCRL(url));
                        } catch (CertificateException | CRLException e) {
                            throw new CRLException("Couldn't download CRL");
                        }
                    }
                }
            }
        } else {
            Log.warning("Certificate " + cert.getSubjectX500Principal().getName().toString() + " have no CRLs");
        }
        // parameters for cert store is collection type, using collection with crl create parameters
        CollectionCertStoreParameters params = new CollectionCertStoreParameters(crlCollection);
        // this parameters are next used for creation of certificate store with crls
        crlStore = CertStore.getInstance("Collection", params);
    }
    return crlCollection;
}
 
Example #26
Source Project: hadoop-ozone   Author: apache   File: TestDefaultProfile.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Generate an Extension with rfc822Name.
 * @param extensionCode - Extension Code.
 * @param value  - email to be added to the certificate
 * @param critical - boolean value that marks the extension as critical.
 * @return - An Extension list with email address.
 * @throws IOException
 */
private Extensions getSANExtension(int extensionCode, String value,
    boolean critical) throws IOException {
  GeneralName extn = new GeneralName(extensionCode,
      value);
  ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();
  extensionsGenerator.addExtension(Extension.subjectAlternativeName, critical,
      new GeneralNames(extn));
  return extensionsGenerator.generate();
}
 
Example #27
Source Project: CapturePacket   Author: huanglqweiwei   File: BouncyCastleSecurityProviderTool.java    License: MIT License 5 votes vote down vote up
/**
 * Converts a list of domain name Subject Alternative Names into ASN1Encodable GeneralNames objects, for use with
 * the Bouncy Castle certificate builder.
 *
 * @param subjectAlternativeNames domain name SANs to convert
 * @return a GeneralNames instance that includes the specifie dsubjectAlternativeNames as DNS name fields
 */
private static GeneralNames getDomainNameSANsAsASN1Encodable(List<String> subjectAlternativeNames) {
    List<GeneralName> encodedSANs = new ArrayList<>(subjectAlternativeNames.size());
    for (String subjectAlternativeName : subjectAlternativeNames) {
        // IP addresses use the IP Address tag instead of the DNS Name tag in the SAN list
        boolean isIpAddress = InetAddresses.isInetAddress(subjectAlternativeName);
        GeneralName generalName = new GeneralName(isIpAddress ? GeneralName.iPAddress : GeneralName.dNSName, subjectAlternativeName);
        encodedSANs.add(generalName);
    }

    return new GeneralNames(encodedSANs.toArray(new GeneralName[encodedSANs.size()]));
}
 
Example #28
Source Project: proxyee   Author: monkeyWie   File: CertUtil.java    License: MIT License 5 votes vote down vote up
/**
 * 动态生成服务器证书,并进行CA签授
 *
 * @param issuer 颁发机构
 */
public static X509Certificate genCert(String issuer, PrivateKey caPriKey, Date caNotBefore,
                                      Date caNotAfter, PublicKey serverPubKey,
                                      String... hosts) throws Exception {
    /* String issuer = "C=CN, ST=GD, L=SZ, O=lee, OU=study, CN=ProxyeeRoot";
    String subject = "C=CN, ST=GD, L=SZ, O=lee, OU=study, CN=" + host;*/
    //根据CA证书subject来动态生成目标服务器证书的issuer和subject
    String subject = Stream.of(issuer.split(", ")).map(item -> {
        String[] arr = item.split("=");
        if ("CN".equals(arr[0])) {
            return "CN=" + hosts[0];
        } else {
            return item;
        }
    }).collect(Collectors.joining(", "));

    //doc from https://www.cryptoworkshop.com/guide/
    JcaX509v3CertificateBuilder jv3Builder = new JcaX509v3CertificateBuilder(new X500Name(issuer),
            //issue#3 修复ElementaryOS上证书不安全问题(serialNumber为1时证书会提示不安全),避免serialNumber冲突,采用时间戳+4位随机数生成
            BigInteger.valueOf(System.currentTimeMillis() + (long) (Math.random() * 10000) + 1000),
            caNotBefore,
            caNotAfter,
            new X500Name(subject),
            serverPubKey);
    //SAN扩展证书支持的域名,否则浏览器提示证书不安全
    GeneralName[] generalNames = new GeneralName[hosts.length];
    for (int i = 0; i < hosts.length; i++) {
        generalNames[i] = new GeneralName(GeneralName.dNSName, hosts[i]);
    }
    GeneralNames subjectAltName = new GeneralNames(generalNames);
    jv3Builder.addExtension(Extension.subjectAlternativeName, false, subjectAltName);
    //SHA256 用SHA1浏览器可能会提示证书不安全
    ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(caPriKey);
    return new JcaX509CertificateConverter().getCertificate(jv3Builder.build(signer));
}
 
Example #29
Source Project: SecuritySample   Author: Catherine22   File: SubjectAlternativeNameImpl.java    License: Apache License 2.0 5 votes vote down vote up
public SubjectAlternativeNameImpl(X509Certificate cert) throws IOException {
	DNSNames = new ArrayList<>();
	byte[] extVal = cert.getExtensionValue(Extension.subjectAlternativeName.getId());
	if (extVal == null)
		return;
	GeneralNames gn = GeneralNames.getInstance(X509ExtensionUtil.fromExtensionValue(extVal));
	GeneralName[] names = gn.getNames();
	for (GeneralName name : names) {
		if (name.getTagNo() == GeneralName.dNSName) {
			String dns = name.getName().toString();
			DNSNames.add(dns);
		}
	}
}
 
Example #30
Source Project: qpid-broker-j   Author: apache   File: TlsResourceBuilder.java    License: Apache License 2.0 5 votes vote down vote up
private static Extension createDistributionPointExtension(final String crlUri) throws CertificateException
{
    try
    {
        final GeneralName generalName = new GeneralName(GeneralName.uniformResourceIdentifier, crlUri);
        final DistributionPointName pointName = new DistributionPointName(new GeneralNames(generalName));
        final DistributionPoint[] points = new DistributionPoint[]{new DistributionPoint(pointName, null, null)};
        return new Extension(Extension.cRLDistributionPoints, false, new CRLDistPoint(points).getEncoded());
    }
    catch (IOException e)
    {
        throw new CertificateException(e);
    }
}