org.bouncycastle.asn1.x509.GeneralNames Java Examples

The following examples show how to use org.bouncycastle.asn1.x509.GeneralNames. 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: AbstractKeyStoreManager.java    From DeviceConnect-Android with 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 File: X509Ext.java    From keystore-explorer with 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 #3
Source File: TlsHelper.java    From nifi with 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 File: SelfSignedP12Certificate.java    From besu with 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 File: TlsHelperTest.java    From nifi with 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 File: CertificateManager.java    From Openfire with 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 #7
Source File: CRLDistributionPointsImpl.java    From SecuritySample with 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 File: TlsHelperTest.java    From localization_nifi with 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 #9
Source File: DefaultProfile.java    From hadoop-ozone with 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 #10
Source File: X509Ext.java    From portecle with 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 #11
Source File: TlsResourceBuilder.java    From qpid-broker-j with Apache License 2.0 6 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);
    }
}
 
Example #12
Source File: TlsResourceBuilder.java    From qpid-broker-j with 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 #13
Source File: EndPointKeyStoreManager.java    From DeviceConnect-Android with 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 #14
Source File: CertificateNamesGeneratorTest.java    From dcos-commons with 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 #15
Source File: SigningCertificate.java    From signer with 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 #16
Source File: CertificateReaderTest.java    From credhub with 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 #17
Source File: CertificateReaderTest.java    From credhub with 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 #18
Source File: X509Ext.java    From keystore-explorer with 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 #19
Source File: Crypto.java    From athenz with 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 #20
Source File: DAuthorityKeyIdentifier.java    From keystore-explorer with 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 File: DAuthorityKeyIdentifier.java    From keystore-explorer with 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 File: DSubjectAlternativeName.java    From keystore-explorer with 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 File: CertificateNamesGeneratorTest.java    From dcos-commons with 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 #24
Source File: CertificateNamesGeneratorTest.java    From dcos-commons with 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 #25
Source File: CertificateNamesGenerator.java    From dcos-commons with 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 #26
Source File: CertificateManagerTest.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * {@link CertificateManager#getServerIdentities(X509Certificate)} should return:
 * <ul>
 *     <li>the 'DNS SRV' subjectAltName value</li>
 *     <li>explicitly not the Common Name</li>
 * </ul>
 *
 * when a certificate contains:
 * <ul>
 *     <li>a subjectAltName entry of type otherName with an ASN.1 Object Identifier of "id-on-dnsSRV"</li>
 * </ul>
 */
@Test
public void testServerIdentitiesDnsSrv() throws Exception
{
    // Setup fixture.
    final String subjectCommonName = "MySubjectCommonName";
    final String subjectAltNameDnsSrv = "MySubjectAltNameXmppAddr";

    final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
            new X500Name( "CN=MyIssuer" ),                                          // Issuer
            BigInteger.valueOf( Math.abs( new SecureRandom().nextInt() ) ),         // Random serial number
            new Date( System.currentTimeMillis() - ( 1000L * 60 * 60 * 24 * 30 ) ), // Not before 30 days ago
            new Date( System.currentTimeMillis() + ( 1000L * 60 * 60 * 24 * 99 ) ), // Not after 99 days from now
            new X500Name( "CN=" + subjectCommonName ),                              // Subject
            subjectKeyPair.getPublic()
    );

    final DERSequence otherName = new DERSequence( new ASN1Encodable[] {DNS_SRV_OID, new DERUTF8String( "_xmpp-server."+subjectAltNameDnsSrv ) });
    final GeneralNames subjectAltNames = new GeneralNames( new GeneralName(GeneralName.otherName, otherName ) );
    builder.addExtension( Extension.subjectAlternativeName, true, subjectAltNames );

    final X509CertificateHolder certificateHolder = builder.build( contentSigner );
    final X509Certificate cert = new JcaX509CertificateConverter().getCertificate( certificateHolder );

    // Execute system under test
    final List<String> serverIdentities = CertificateManager.getServerIdentities( cert );

    // Verify result
    assertEquals( 1, serverIdentities.size() );
    assertTrue( serverIdentities.contains( subjectAltNameDnsSrv ));
    assertFalse( serverIdentities.contains( subjectCommonName ) );
}
 
Example #27
Source File: X509Ca.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static Extension createCertificateIssuerExtension(X500Name certificateIssuer) {
  try {
    GeneralNames generalNames = new GeneralNames(new GeneralName(certificateIssuer));
    return new Extension(Extension.certificateIssuer, true, generalNames.getEncoded());
  } catch (IOException ex) {
    throw new IllegalArgumentException("error encoding reason: " + ex.getMessage(), ex);
  }
}
 
Example #28
Source File: DIssuerAlternativeName.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
private void prepopulateWithValue(byte[] value) throws IOException {
	GeneralNames issuerAlternativeName = GeneralNames.getInstance(value);

	if (issuerAlternativeName != null) {
		jgnAlternativeName.setGeneralNames(issuerAlternativeName);
	}
}
 
Example #29
Source File: CertificateManagerTest.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * {@link CertificateManager#getServerIdentities(X509Certificate)} should return:
 * <ul>
 *     <li>the DNS subjectAltName value</li>
 *     <li>explicitly not the Common Name</li>
 * </ul>
 *
 * when a certificate contains:
 * <ul>
 *     <li>a subjectAltName entry of type DNS </li>
 * </ul>
 */
@Test
public void testServerIdentitiesDNS() throws Exception
{
    // Setup fixture.
    final String subjectCommonName = "MySubjectCommonName";
    final String subjectAltNameDNS = "MySubjectAltNameDNS";

    final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
            new X500Name( "CN=MyIssuer" ),                                          // Issuer
            BigInteger.valueOf( Math.abs( new SecureRandom().nextInt() ) ),         // Random serial number
            new Date( System.currentTimeMillis() - ( 1000L * 60 * 60 * 24 * 30 ) ), // Not before 30 days ago
            new Date( System.currentTimeMillis() + ( 1000L * 60 * 60 * 24 * 99 ) ), // Not after 99 days from now
            new X500Name( "CN=" + subjectCommonName ),                              // Subject
            subjectKeyPair.getPublic()
    );

    final GeneralNames generalNames = new GeneralNames(new GeneralName(GeneralName.dNSName, subjectAltNameDNS));

    builder.addExtension( Extension.subjectAlternativeName, false, generalNames );

    final X509CertificateHolder certificateHolder = builder.build( contentSigner );
    final X509Certificate cert = new JcaX509CertificateConverter().getCertificate( certificateHolder );

    // Execute system under test
    final List<String> serverIdentities = CertificateManager.getServerIdentities( cert );

    // Verify result
    assertEquals( 1, serverIdentities.size() );
    assertTrue( serverIdentities.contains( subjectAltNameDNS ) );
    assertFalse( serverIdentities.contains( subjectCommonName ) );
}
 
Example #30
Source File: CertificateManagerTest.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * {@link CertificateManager#getServerIdentities(X509Certificate)} should return:
 * <ul>
 *     <li>the DNS subjectAltName value</li>
 *     <li>the 'xmppAddr' subjectAltName value</li>
 *     <li>explicitly not the Common Name</li>
 * </ul>
 *
 * when a certificate contains:
 * <ul>
 *     <li>a subjectAltName entry of type DNS </li>
 *     <li>a subjectAltName entry of type otherName with an ASN.1 Object Identifier of "id-on-xmppAddr"</li>
 * </ul>
 */
@Test
public void testServerIdentitiesXmppAddrAndDNS() throws Exception
{
    // Setup fixture.
    final String subjectCommonName = "MySubjectCommonName";
    final String subjectAltNameXmppAddr = "MySubjectAltNameXmppAddr";
    final String subjectAltNameDNS = "MySubjectAltNameDNS";

    final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
            new X500Name( "CN=MyIssuer" ),                                          // Issuer
            BigInteger.valueOf( Math.abs( new SecureRandom().nextInt() ) ),         // Random serial number
            new Date( System.currentTimeMillis() - ( 1000L * 60 * 60 * 24 * 30 ) ), // Not before 30 days ago
            new Date( System.currentTimeMillis() + ( 1000L * 60 * 60 * 24 * 99 ) ), // Not after 99 days from now
            new X500Name( "CN=" + subjectCommonName ),                              // Subject
            subjectKeyPair.getPublic()
    );

    final DERSequence otherName = new DERSequence( new ASN1Encodable[] { XMPP_ADDR_OID, new DERUTF8String( subjectAltNameXmppAddr ) });
    final GeneralNames subjectAltNames = new GeneralNames( new GeneralName[] {
            new GeneralName( GeneralName.otherName, otherName ),
            new GeneralName( GeneralName.dNSName, subjectAltNameDNS )
    });
    builder.addExtension( Extension.subjectAlternativeName, true, subjectAltNames );

    final X509CertificateHolder certificateHolder = builder.build( contentSigner );
    final X509Certificate cert = new JcaX509CertificateConverter().getCertificate( certificateHolder );

    // Execute system under test
    final List<String> serverIdentities = CertificateManager.getServerIdentities( cert );

    // Verify result
    assertEquals( 2, serverIdentities.size() );
    assertTrue( serverIdentities.contains( subjectAltNameXmppAddr ));
    assertFalse( serverIdentities.contains( subjectCommonName ) );
}