org.bouncycastle.asn1.x509.GeneralName Java Examples

The following examples show how to use org.bouncycastle.asn1.x509.GeneralName. 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: JGeneralNames.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
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 #2
Source File: TestDefaultProfile.java    From hadoop-ozone with 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 #3
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 #4
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 #5
Source File: TestDefaultProfile.java    From hadoop-ozone with 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 #6
Source File: Actions.java    From xipki with 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 #7
Source File: BaseCmpResponder.java    From xipki with 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 #8
Source File: SubjectAlternativeName.java    From vespa with 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 #9
Source File: DAccessDescriptionChooser.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
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 #10
Source File: BasicCertificate.java    From signer with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
    * 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 #11
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 #12
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 #13
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 #14
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 #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: 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 #17
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 #18
Source File: JGeneralName.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
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 #19
Source File: AbstractCRLUtils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private String getUrl(DistributionPointName distributionPoint) {
	if ((distributionPoint != null) && (DistributionPointName.FULL_NAME == distributionPoint.getType())) {
		final GeneralNames generalNames = (GeneralNames) distributionPoint.getName();
		if ((generalNames != null) && (generalNames.getNames() != null && generalNames.getNames().length > 0)) {
			for (GeneralName generalName : generalNames.getNames()) {
				if (GeneralName.uniformResourceIdentifier == generalName.getTagNo()) {
					ASN1String str = (ASN1String) ((DERTaggedObject) generalName.toASN1Primitive()).getObject();
					return str.getString();
				}
			}
		}
	}
	return null;
}
 
Example #20
Source File: SparkTrustManager.java    From Spark with 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 #21
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 #22
Source File: SubjectAlternativeNameHolder.java    From AndroidHttpCapture with MIT License 5 votes vote down vote up
private ASN1Encodable parseGeneralName(List<?> nameEntry) {
    if (nameEntry == null || nameEntry.size() != 2) {
        throw new IllegalArgumentException(nameEntry != null ? String.valueOf(nameEntry) : "nameEntry is null");
    }
    String tag = String.valueOf(nameEntry.get(0));
    Matcher m = TAGS_PATTERN.matcher(tag);
    if (m.matches()) {
        return new GeneralName(Integer.valueOf(tag),
                String.valueOf(nameEntry.get(1)));
    }
    throw new IllegalArgumentException(String.valueOf(nameEntry));
}
 
Example #23
Source File: JGeneralNames.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
private void selectGeneralNameInTable(GeneralName generalName) {
	for (int i = 0; i < jtGeneralNames.getRowCount(); i++) {
		if (generalName.equals(jtGeneralNames.getValueAt(i, 0))) {
			jtGeneralNames.changeSelection(i, 0, false, false);
			return;
		}
	}
}
 
Example #24
Source File: Crypto.java    From athenz with Apache License 2.0 5 votes vote down vote up
public static String extractX509CSREmail(PKCS10CertificationRequest certReq) {
    List<String> emails = extractX509CSRSANField(certReq, GeneralName.rfc822Name);
    if (emails.size() == 0) {
        return null;
    }
    return emails.get(0);
}
 
Example #25
Source File: PkiUtil.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private static PKCS10CertificationRequestBuilder addSubjectAlternativeNames(PKCS10CertificationRequestBuilder p10Builder, List<String> sanList)
        throws IOException {
    GeneralName[] generalNames = sanList
            .stream()
            .map(address -> new GeneralName(GeneralName.dNSName, address))
            .toArray(GeneralName[]::new);

    GeneralNames subjectAltNames = new GeneralNames(generalNames);
    ExtensionsGenerator extGen = new ExtensionsGenerator();
    extGen.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
    return p10Builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate());
}
 
Example #26
Source File: Crypto.java    From athenz with Apache License 2.0 5 votes vote down vote up
public static String generateX509CSR(PrivateKey privateKey, PublicKey publicKey,
                                     String x500Principal, GeneralName[] sanArray) throws OperatorCreationException, IOException {

    // Create Distinguished Name

    X500Principal subject = new X500Principal(x500Principal);

    // Create ContentSigner

    JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder(Crypto.RSA_SHA256);
    ContentSigner signer = csBuilder.build(privateKey);

    // Create the CSR

    PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(
            subject, publicKey);

    // Add SubjectAlternativeNames (SAN) if specified
    ///CLOVER:OFF
    if (sanArray != null) {
        ///CLOVER:ON
        ExtensionsGenerator extGen = new ExtensionsGenerator();
        GeneralNames subjectAltNames = new GeneralNames(sanArray);
        extGen.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
        p10Builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate());
    }

    PKCS10CertificationRequest csr = p10Builder.build(signer);

    // write to openssl PEM format

    PemObject pemObject = new PemObject("CERTIFICATE REQUEST", csr.getEncoded());
    StringWriter strWriter;
    try (JcaPEMWriter pemWriter = new JcaPEMWriter(strWriter = new StringWriter())) {
        pemWriter.writeObject(pemObject);
    }
    return strWriter.toString();
}
 
Example #27
Source File: DSSASN1Utils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * This method returns a new IssuerSerial based on the certificate token
 *
 * @param certToken
 *            the certificate token
 * @return a IssuerSerial
 */
public static IssuerSerial getIssuerSerial(final CertificateToken certToken) {
	final X500Name issuerX500Name = getX509CertificateHolder(certToken).getIssuer();
	final GeneralName generalName = new GeneralName(issuerX500Name);
	final GeneralNames generalNames = new GeneralNames(generalName);
	final BigInteger serialNumber = certToken.getCertificate().getSerialNumber();
	return new IssuerSerial(generalNames, serialNumber);
}
 
Example #28
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 'xmppAddr' 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-xmppAddr"</li>
 * </ul>
 */
@Test
public void testServerIdentitiesXmppAddr() throws Exception
{
    // Setup fixture.
    final String subjectCommonName = "MySubjectCommonName";
    final String subjectAltNameXmppAddr = "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[] { XMPP_ADDR_OID, new DERUTF8String( subjectAltNameXmppAddr ) });
    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( subjectAltNameXmppAddr ));
    assertFalse( serverIdentities.contains( subjectCommonName ) );
}
 
Example #29
Source File: InstanceClientRefresh.java    From athenz with Apache License 2.0 5 votes vote down vote up
public static String generateCSR(String domainName, String serviceName,
        String instanceId, String dnsSuffix, PrivateKey key) {
    
    final String dn = "cn=" + domainName + "." + serviceName + ",o=Athenz";
    
    // now let's generate our dsnName field based on our principal's details
    
    StringBuilder dnsName = new StringBuilder(128);
    dnsName.append(serviceName);
    dnsName.append('.');
    dnsName.append(domainName.replace('.', '-'));
    dnsName.append('.');
    dnsName.append(dnsSuffix);
    
    GeneralName[] sanArray = new GeneralName[2];
    sanArray[0] = new GeneralName(GeneralName.dNSName, new DERIA5String(dnsName.toString()));
    
    // next we include our instance id
    
    StringBuilder dnsInstance = new StringBuilder(128);
    dnsInstance.append(instanceId);
    dnsInstance.append(".instanceid.athenz.");
    dnsInstance.append(dnsSuffix);
    
    sanArray[1] = new GeneralName(GeneralName.dNSName, new DERIA5String(dnsInstance.toString()));
    
    String csr = null;
    try {
        csr = Crypto.generateX509CSR(key, dn, sanArray);
    } catch (OperatorCreationException | IOException ex) {
        System.err.println(ex.getMessage());
    }
    
    return csr;
}
 
Example #30
Source File: JGeneralNames.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
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();
	}
}