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

The following examples show how to use org.bouncycastle.asn1.x509.GeneralName. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: hadoop-ozone   Source 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 2
Source Project: xipki   Source File: Actions.java    License: Apache License 2.0 6 votes vote down vote up
public static List<String> extractOcspUrls(AuthorityInformationAccess aia)
    throws CertificateEncodingException {
  AccessDescription[] accessDescriptions = aia.getAccessDescriptions();
  List<AccessDescription> ocspAccessDescriptions = new LinkedList<>();
  for (AccessDescription accessDescription : accessDescriptions) {
    if (accessDescription.getAccessMethod().equals(X509ObjectIdentifiers.id_ad_ocsp)) {
      ocspAccessDescriptions.add(accessDescription);
    }
  }

  final int n = ocspAccessDescriptions.size();
  List<String> ocspUris = new ArrayList<>(n);
  for (int i = 0; i < n; i++) {
    GeneralName accessLocation = ocspAccessDescriptions.get(i).getAccessLocation();
    if (accessLocation.getTagNo() == GeneralName.uniformResourceIdentifier) {
      String ocspUri = ((ASN1String) accessLocation.getName()).getString();
      ocspUris.add(ocspUri);
    }
  }

  return ocspUris;
}
 
Example 3
Source Project: hadoop-ozone   Source File: TestDefaultProfile.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests that  invalid extensions cause a failure in validation. We will fail
 * if rfc222 type names are added, we also add the extension as both
 * critical and non-critical fashion to verify that the we catch both cases.
 *
 * @throws SCMSecurityException - on Error.
 */

@Test
public void testInvalidExtensionsWithEmail()
    throws IOException, OperatorCreationException {
  Extensions emailExtension = getSANExtension(GeneralName.rfc822Name,
      "[email protected]", false);
  PKCS10CertificationRequest csr = getInvalidCSR(keyPair, emailExtension);
  assertFalse(testApprover.verfiyExtensions(csr));

  emailExtension = getSANExtension(GeneralName.rfc822Name, "bilbo" +
      "@apache.org", true);
  csr = getInvalidCSR(keyPair, emailExtension);
  assertFalse(testApprover.verfiyExtensions(csr));

}
 
Example 4
Source Project: hadoop-ozone   Source File: TestDefaultProfile.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Assert that if DNS is marked critical our PKI profile will reject it.
 * @throws IOException - on Error.
 * @throws OperatorCreationException - on Error.
 */
@Test
public void testInvalidExtensionsWithCriticalDNS() throws IOException,
    OperatorCreationException {
  Extensions dnsExtension = getSANExtension(GeneralName.dNSName,
      "ozone.hadoop.org",
      true);
  PKCS10CertificationRequest csr = getInvalidCSR(keyPair, dnsExtension);
  assertFalse(testApprover.verfiyExtensions(csr));
  // This tests should pass, hence the assertTrue
  dnsExtension = getSANExtension(GeneralName.dNSName,
      "ozone.hadoop.org",
      false);
  csr = getInvalidCSR(keyPair, dnsExtension);
  assertTrue(testApprover.verfiyExtensions(csr));
}
 
Example 5
Source Project: keystore-explorer   Source 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 6
Source Project: localization_nifi   Source 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   Source 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
private void editGeneralName() {
	Container container = getTopLevelAncestor();

	DGeneralNameChooser dGeneralNameChooser = null;

	if (container instanceof JDialog) {
		dGeneralNameChooser = new DGeneralNameChooser((JDialog) container, title, generalName);
	} else {
		dGeneralNameChooser = new DGeneralNameChooser((JFrame) container, title, generalName);
	}
	dGeneralNameChooser.setLocationRelativeTo(container);
	dGeneralNameChooser.setVisible(true);

	GeneralName newGeneralName = dGeneralNameChooser.getGeneralName();

	if (newGeneralName == null) {
		return;
	}

	setGeneralName(newGeneralName);
}
 
Example 9
Source Project: nifi   Source 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 10
@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
/**
    * Returns the AuthorityInfoAccess extension value on list format.<br>
    * Otherwise, returns <b>list empty</b>.<br>
    * @return List Authority info access list
    */
public List<String> getAuthorityInfoAccess() {
	List<String> address = new ArrayList<String>();
	try {
		byte[] authorityInfoAccess = certificate.getExtensionValue(Extension.authorityInfoAccess.getId());
		if (authorityInfoAccess != null && authorityInfoAccess.length > 0) {
			AuthorityInformationAccess infoAccess = AuthorityInformationAccess.getInstance(
					JcaX509ExtensionUtils.parseExtensionValue(authorityInfoAccess));
			for (AccessDescription desc : infoAccess.getAccessDescriptions())
				if (desc.getAccessLocation().getTagNo() == GeneralName.uniformResourceIdentifier)
					address.add(((DERIA5String) desc.getAccessLocation().getName()).getString());
		}
		return address;
	} catch (Exception error) {
		logger.info(error.getMessage());
		return address;
	}
}
 
Example 12
private void okPressed() {
	ASN1ObjectIdentifier accessMethod = joiAccessMethod.getObjectId();

	if (accessMethod == null) {
		JOptionPane.showMessageDialog(this,
				res.getString("DAccessDescriptionChooser.AccessMethodValueReq.message"), getTitle(),
				JOptionPane.WARNING_MESSAGE);
		return;
	}

	GeneralName accessLocation = jgnAccessLocation.getGeneralName();

	if (accessLocation == null) {
		JOptionPane.showMessageDialog(this,
				res.getString("DAccessDescriptionChooser.AccessLocationValueReq.message"), getTitle(),
				JOptionPane.WARNING_MESSAGE);
		return;
	}

	accessDescription = new AccessDescription(accessMethod, accessLocation);

	closeDialog();
}
 
Example 13
private void addPressed() {
	Container container = getTopLevelAncestor();

	DGeneralNameChooser dGeneralNameChooser = null;

	if (container instanceof JDialog) {
		dGeneralNameChooser = new DGeneralNameChooser((JDialog) container, title, null);
	} else {
		dGeneralNameChooser = new DGeneralNameChooser((JFrame) container, title, null);
	}
	dGeneralNameChooser.setLocationRelativeTo(container);
	dGeneralNameChooser.setVisible(true);

	GeneralName newGeneralName = dGeneralNameChooser.getGeneralName();

	if (newGeneralName == null) {
		return;
	}

	getGeneralNamesTableModel().addRow(newGeneralName);

	selectGeneralNameInTable(newGeneralName);
	updateButtonControls();
}
 
Example 14
Source Project: vespa   Source File: SubjectAlternativeName.java    License: Apache License 2.0 6 votes vote down vote up
private String getValue(GeneralName bcGeneralName) {
    ASN1Encodable name = bcGeneralName.getName();
    switch (bcGeneralName.getTagNo()) {
        case GeneralName.rfc822Name:
        case GeneralName.dNSName:
        case GeneralName.uniformResourceIdentifier:
            return DERIA5String.getInstance(name).getString();
        case GeneralName.directoryName:
            return X500Name.getInstance(name).toString();
        case GeneralName.iPAddress:
            byte[] octets = DEROctetString.getInstance(name.toASN1Primitive()).getOctets();
            try {
                return InetAddress.getByAddress(octets).getHostAddress();
            } catch (UnknownHostException e) {
                // Only thrown if IP address is of invalid length, which is an illegal argument
                throw new IllegalArgumentException(e);
            }
        default:
            return name.toString();
    }
}
 
Example 15
Source Project: xipki   Source File: BaseCmpResponder.java    License: Apache License 2.0 6 votes vote down vote up
protected PKIMessage buildErrorPkiMessage(ASN1OctetString tid,
    PKIHeader requestHeader, int failureCode, String statusText) {
  GeneralName respRecipient = requestHeader.getSender();

  PKIHeaderBuilder respHeader = new PKIHeaderBuilder(
      requestHeader.getPvno().getValue().intValue(), getSender(), respRecipient);
  respHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
  if (tid != null) {
    respHeader.setTransactionID(tid);
  }

  ASN1OctetString senderNonce = requestHeader.getSenderNonce();
  if (senderNonce != null) {
    respHeader.setRecipNonce(senderNonce);
  }

  PKIStatusInfo status = generateRejectionStatus(failureCode, statusText);
  ErrorMsgContent error = new ErrorMsgContent(status);
  PKIBody body = new PKIBody(PKIBody.TYPE_ERROR, error);

  return new PKIMessage(respHeader.build(), body);
}
 
Example 16
Source Project: Openfire   Source 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 17
Source Project: nifi   Source 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 18
Source Project: hadoop-ozone   Source File: CertificateSignRequest.java    License: Apache License 2.0 5 votes vote down vote up
public CertificateSignRequest.Builder addServiceName(
    String serviceName) {
  Preconditions.checkNotNull(
      serviceName, "Service Name cannot be null");

  this.addAltName(GeneralName.otherName, serviceName);
  return this;
}
 
Example 19
Source Project: hadoop-ozone   Source File: CertificateSignRequest.java    License: Apache License 2.0 5 votes vote down vote up
private CertificateSignRequest.Builder addAltName(int tag, String name) {
  if (altNames == null) {
    altNames = new ArrayList<>();
  }
  if (tag == GeneralName.otherName) {
    ASN1Object ono = addOtherNameAsn1Object(name);

    altNames.add(new GeneralName(tag, ono));
  } else {
    altNames.add(new GeneralName(tag, name));
  }
  return this;
}
 
Example 20
Source Project: hadoop-ozone   Source File: CertificateSignRequest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * addOtherNameAsn1Object requires special handling since
 * Bouncy Castle does not support othername as string.
 * @param name
 * @return
 */
private ASN1Object addOtherNameAsn1Object(String name) {
  // Below oid is copied from this URL:
  // https://docs.microsoft.com/en-us/windows/win32/adschema/a-middlename
  final String otherNameOID = "2.16.840.1.113730.3.1.34";
  ASN1EncodableVector otherName = new ASN1EncodableVector();
  otherName.add(new ASN1ObjectIdentifier(otherNameOID));
  otherName.add(new DERTaggedObject(
      true, GeneralName.otherName, new DERUTF8String(name)));
  return new DERTaggedObject(
      false, 0, new DERSequence(otherName));
}
 
Example 21
Source Project: hadoop-ozone   Source File: CertificateSignRequest.java    License: Apache License 2.0 5 votes vote down vote up
private Optional<Extension> getSubjectAltNameExtension() throws
    IOException {
  if (altNames != null) {
    return Optional.of(new Extension(Extension.subjectAlternativeName,
        false, new DEROctetString(new GeneralNames(
        altNames.toArray(new GeneralName[altNames.size()])))));
  }
  return Optional.empty();
}
 
Example 22
Source Project: cloudstack   Source File: CertUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGenerateCertificate() throws Exception {
    final KeyPair clientKeyPair = CertUtils.generateRandomKeyPair(1024);
    final List<String> domainNames = Arrays.asList("domain1.com", "www.2.domain2.com", "3.domain3.com");
    final List<String> addressList = Arrays.asList("1.2.3.4", "192.168.1.1", "2a02:120b:2c16:f6d0:d9df:8ebc:e44a:f181");

    final X509Certificate clientCert = CertUtils.generateV3Certificate(caCertificate, caKeyPair, clientKeyPair.getPublic(),
            "CN=domain.example", "SHA256WithRSAEncryption", 10, domainNames, addressList);

    clientCert.verify(caKeyPair.getPublic());
    Assert.assertEquals(clientCert.getIssuerDN(), caCertificate.getIssuerDN());
    Assert.assertEquals(clientCert.getSigAlgName(), "SHA256WITHRSA");
    Assert.assertArrayEquals(clientCert.getPublicKey().getEncoded(), clientKeyPair.getPublic().getEncoded());
    Assert.assertNotNull(clientCert.getSubjectAlternativeNames());

    for (final List<?> altNames : clientCert.getSubjectAlternativeNames()) {
        Assert.assertTrue(altNames.size() == 2);
        final Object first = altNames.get(0);
        final Object second = altNames.get(1);
        if (first instanceof Integer && ((Integer) first) == GeneralName.iPAddress) {
            Assert.assertTrue(addressList.contains((String) second));
        }
        if (first instanceof Integer && ((Integer) first) == GeneralName.dNSName) {
            Assert.assertTrue(domainNames.contains((String) second));
        }
    }
}
 
Example 23
Source Project: Openfire   Source File: CertificateManagerTest.java    License: 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 24
Source Project: PowerTunnel   Source File: SubjectAlternativeNameHolder.java    License: MIT License 5 votes vote down vote up
public void addAll(Collection<List<?>> subjectAlternativeNames) {
    if (subjectAlternativeNames != null) {
        for (List<?> each : subjectAlternativeNames) {
            if (isValidNameEntry(each)) {
                int tag = Integer.valueOf(String.valueOf(each.get(0)));
                String name = String.valueOf(each.get(1));
                sans.add(new GeneralName(tag, name));
            } else {
                log.warn("Invalid name entry ignored: {}", each);
            }
            
        }
    }
}
 
Example 25
Source Project: CapturePacket   Source 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 26
Source Project: FairEmail   Source File: EmailService.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static List<String> getDnsNames(X509Certificate certificate) throws CertificateParsingException {
    List<String> result = new ArrayList<>();

    Collection<List<?>> altNames = certificate.getSubjectAlternativeNames();
    if (altNames == null)
        return result;

    for (List altName : altNames)
        if (altName.get(0).equals(GeneralName.dNSName))
            result.add((String) altName.get(1));

    return result;
}
 
Example 27
Source Project: proxyee   Source 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 28
public void addAll(Collection<List<?>> subjectAlternativeNames) {
    if (subjectAlternativeNames != null) {
        for (List<?> each : subjectAlternativeNames) {
            if (isValidNameEntry(each)) {
                int tag = Integer.valueOf(String.valueOf(each.get(0)));
                String name = String.valueOf(each.get(1));
                sans.add(new GeneralName(tag, name));
            } else {
                log.warn("Invalid name entry ignored: {}", each);
            }
            
        }
    }
}
 
Example 29
Source Project: qpid-broker-j   Source 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);
    }
}
 
Example 30
private void editSelectedGeneralName() {
	int selectedRow = jtGeneralNames.getSelectedRow();

	if (selectedRow != -1) {
		GeneralName generalName = (GeneralName) jtGeneralNames.getValueAt(selectedRow, 0);

		Container container = getTopLevelAncestor();

		DGeneralNameChooser dGeneralNameChooser = null;

		if (container instanceof JDialog) {
			dGeneralNameChooser = new DGeneralNameChooser((JDialog) container, title, generalName);
		} else if (container instanceof JFrame) {
			dGeneralNameChooser = new DGeneralNameChooser((JFrame) container, title, generalName);
		}
		dGeneralNameChooser.setLocationRelativeTo(container);
		dGeneralNameChooser.setVisible(true);

		GeneralName newGeneralName = dGeneralNameChooser.getGeneralName();

		if (newGeneralName == null) {
			return;
		}

		getGeneralNamesTableModel().removeRow(selectedRow);
		getGeneralNamesTableModel().addRow(newGeneralName);

		selectGeneralNameInTable(newGeneralName);
		updateButtonControls();
	}
}