Java Code Examples for org.bouncycastle.asn1.x509.GeneralNames#getInstance()

The following examples show how to use org.bouncycastle.asn1.x509.GeneralNames#getInstance() . 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: 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 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: X509Ext.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
private String getIssuerAlternativeNameStringValue(byte[] value) throws IOException {
	// @formatter:off

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

	// @formatter:on

	StringBuilder sb = new StringBuilder();

	GeneralNames issuerAltName = GeneralNames.getInstance(value);

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

	return sb.toString();
}
 
Example 4
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 5
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 6
Source File: PublicCaInfo.java    From xipki with Apache License 2.0 6 votes vote down vote up
public PublicCaInfo(X509Cert caCert, CaUris caUris, ConfPairs extraControl)
    throws OperationException {
  this.caCert = Args.notNull(caCert, "caCert");
  this.caUris = (caUris == null) ? CaUris.EMPTY_INSTANCE : caUris;
  this.issuer = caCert.getIssuer();
  this.serialNumber = caCert.getSerialNumber();
  this.subject = caCert.getSubject();
  this.c14nSubject = X509Util.canonicalizName(subject);
  this.subjectKeyIdentifier = caCert.getSubjectKeyId();
  this.extraControl = extraControl;

  byte[] encodedSubjectAltName = caCert.getExtensionCoreValue(Extension.subjectAlternativeName);
  if (encodedSubjectAltName == null) {
    subjectAltName = null;
  } else {
    try {
      subjectAltName = GeneralNames.getInstance(encodedSubjectAltName);
    } catch (RuntimeException ex) {
      throw new OperationException(ErrorCode.INVALID_EXTENSION,
          "invalid SubjectAltName extension in CA certificate");
    }
  }
}
 
Example 7
Source File: SubjectAlternativeNameImpl.java    From SecuritySample with Apache License 2.0 5 votes vote down vote up
public SubjectAlternativeNameImpl(X509Certificate cert) throws IOException {
	DNSNames = new ArrayList<>();
	byte[] extVal = cert.getExtensionValue(Extension.subjectAlternativeName.getId());
	if (extVal == null)
		return;
	GeneralNames gn = GeneralNames.getInstance(X509ExtensionUtil.fromExtensionValue(extVal));
	GeneralName[] names = gn.getNames();
	for (GeneralName name : names) {
		if (name.getTagNo() == GeneralName.dNSName) {
			String dns = name.getName().toString();
			DNSNames.add(dns);
		}
	}
}
 
Example 8
Source File: X509CertificateUtils.java    From vespa with Apache License 2.0 5 votes vote down vote up
public static List<SubjectAlternativeName> getSubjectAlternativeNames(X509Certificate certificate) {
    try {
        byte[] extensionValue = certificate.getExtensionValue(SUBJECT_ALTERNATIVE_NAMES.getOId());
        if (extensionValue == null) return Collections.emptyList();
        ASN1Encodable asn1Encodable = ASN1Primitive.fromByteArray(extensionValue);
        if (asn1Encodable instanceof ASN1OctetString) {
            asn1Encodable = ASN1Primitive.fromByteArray(((ASN1OctetString) asn1Encodable).getOctets());
        }
        GeneralNames names = GeneralNames.getInstance(asn1Encodable);
        return SubjectAlternativeName.fromGeneralNames(names);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 9
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 10
Source File: DSubjectAlternativeName.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 subjectAlternativeName = GeneralNames.getInstance(value);

	if (subjectAlternativeName != null) {
		jgnAlternativeName.setGeneralNames(subjectAlternativeName);
	}
}
 
Example 11
Source File: CSRParser.java    From acme_client with MIT License 4 votes vote down vote up
public static Set<String> getDomains(byte[] csrBytes) throws IOException {

        Set<String> domains = new HashSet<>();

        JcaPKCS10CertificationRequest p10Object = new JcaPKCS10CertificationRequest(csrBytes);

        for(RDN rdn : p10Object.getSubject().getRDNs()){
            String id = rdn.getFirst().getType().getId();
            if(COMMON_NAME.equals(id)){
                String commonName = rdn.getFirst().getValue().toString();
                domains.add(commonName);
            }
        }

        for(Attribute attribute : p10Object.getAttributes(EXTENSION_REQUEST_IDENTIFIER)){

            Iterator<ASN1Encodable> attrValIt = attribute.getAttrValues().iterator();
            while (attrValIt.hasNext()){

                Iterator<ASN1Encodable> seqIt = ((DERSequence) attrValIt.next()).iterator();

                while (seqIt.hasNext()){
                    DERSequence seq = (DERSequence) seqIt.next();
                    ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) seq.getObjectAt(0);
                    if (SUBJECT_ALTERNATIVE_NAME.equals(oid.getId())) {
                        DEROctetString str = (DEROctetString) seq.getObjectAt(1);

                        GeneralNames names = GeneralNames.getInstance(str.getOctets());

                        for(String domain : names.toString().split("\\s+")) {
                            if(!domain.endsWith(":")){
                                domains.add(domain);
                            }
                        }

                    }
                }

            }

        }

        return domains;
    }
 
Example 12
Source File: CertificateReader.java    From credhub with Apache License 2.0 4 votes vote down vote up
public GeneralNames getAlternativeNames() {
  final Extension encodedAlternativeNames = certificateHolder
    .getExtension(Extension.subjectAlternativeName);
  return encodedAlternativeNames != null ? GeneralNames
    .getInstance(encodedAlternativeNames.getParsedValue()) : null;
}
 
Example 13
Source File: X509Ext.java    From keystore-explorer with GNU General Public License v3.0 4 votes vote down vote up
private String getDistributionPointNameString(DistributionPointName distributionPointName, String baseIndent)
		throws IOException {
	// @formatter:off

	/*
	 * DistributionPointName ::= CHOICE {
	 * 		fullname [0] GeneralNames,
	 * 		nameRelativeToCRLIssuer [1] RelativeDistinguishedName
	 * }
	 *
	 * RelativeDistinguishedName ::= SET SIZE (1 .. MAX) OF
	 * AttributeTypeAndValue
	 *
	 * AttributeTypeAndValue ::= ASN1Sequence { type AttributeType, value
	 * AttributeValue }
	 */

	// @formatter: on

	StringBuilder sb = new StringBuilder();

	sb.append(baseIndent);
	sb.append(res.getString("DistributionPointName"));
	sb.append(NEWLINE);

	if (distributionPointName.getType() == DistributionPointName.FULL_NAME) {
		sb.append(baseIndent);
		sb.append(INDENT);
		sb.append(res.getString("DistributionPointFullName"));
		sb.append(NEWLINE);

		GeneralNames generalNames = GeneralNames.getInstance(distributionPointName.getName());

		for (GeneralName generalName : generalNames.getNames()) {
			sb.append(baseIndent);
			sb.append(INDENT);
			sb.append(INDENT);
			sb.append(GeneralNameUtil.toString(generalName));
			sb.append(NEWLINE);
		}
	} else {
		// DistributionPointName.TAG_NAMERELATIVETOCRLISSUER
		sb.append(baseIndent);
		sb.append(INDENT);
		sb.append(res.getString("DistributionPointNameRelativeToCrlIssuer"));
		sb.append(NEWLINE);

		RDN rdn = RDN.getInstance(distributionPointName.getName());

		for (AttributeTypeAndValue attributeTypeAndValue : rdn.getTypesAndValues()) {
			ASN1ObjectIdentifier attributeType = attributeTypeAndValue.getType();
			ASN1Encodable attributeValue = attributeTypeAndValue.getValue();

			String attributeTypeStr = getAttributeTypeString(attributeType);
			String attributeValueStr = getAttributeValueString(attributeType, attributeValue);

			sb.append(baseIndent);
			sb.append(INDENT);
			sb.append(INDENT);
			sb.append(MessageFormat.format("{0}={1}", attributeTypeStr, attributeValueStr));
			sb.append(NEWLINE);
		}
	}

	return sb.toString();
}
 
Example 14
Source File: ExtensionsChecker.java    From xipki with Apache License 2.0 4 votes vote down vote up
private GeneralName[] getRequestedSubjectAltNames(X500Name requestedSubject,
    Extensions requestedExtns) throws CertprofileException, BadCertTemplateException {
  ASN1Encodable extValue = (requestedExtns == null) ? null
      : requestedExtns.getExtensionParsedValue(Extension.subjectAlternativeName);

  Map<ASN1ObjectIdentifier, GeneralNameTag> subjectToSubjectAltNameModes =
      certprofile.getSubjectToSubjectAltNameModes();
  if (extValue == null && subjectToSubjectAltNameModes == null) {
    return null;
  }

  GeneralNames reqNames = (extValue == null) ? null : GeneralNames.getInstance(extValue);

  Set<GeneralNameMode> subjectAltNameModes = certprofile.getSubjectAltNameModes();
  if (subjectAltNameModes == null && subjectToSubjectAltNameModes == null) {
    return (reqNames == null) ? null : reqNames.getNames();
  }

  List<GeneralName> grantedNames = new LinkedList<>();
  // copy the required attributes of Subject
  if (subjectToSubjectAltNameModes != null) {
    X500Name grantedSubject = certprofile.getSubject(requestedSubject).getGrantedSubject();

    for (ASN1ObjectIdentifier attrType : subjectToSubjectAltNameModes.keySet()) {
      GeneralNameTag tag = subjectToSubjectAltNameModes.get(attrType);

      RDN[] rdns = grantedSubject.getRDNs(attrType);
      if (rdns == null || rdns.length == 0) {
        rdns = requestedSubject.getRDNs(attrType);
      }

      if (rdns == null || rdns.length == 0) {
        continue;
      }

      for (RDN rdn : rdns) {
        String rdnValue = X509Util.rdnValueToString(rdn.getFirst().getValue());
        switch (tag) {
          case rfc822Name:
            grantedNames.add(new GeneralName(tag.getTag(), rdnValue.toLowerCase()));
            break;
          case DNSName:
          case uniformResourceIdentifier:
          case IPAddress:
          case directoryName:
          case registeredID:
            grantedNames.add(new GeneralName(tag.getTag(), rdnValue));
            break;
          default:
            throw new IllegalStateException(
                "should not reach here, unknown GeneralName tag " + tag);
        } // end switch (tag)
      }
    }
  }

  // copy the requested SubjectAltName entries
  if (reqNames != null) {
    GeneralName[] reqL = reqNames.getNames();
    for (int i = 0; i < reqL.length; i++) {
      grantedNames.add(reqL[i]);
    }
  }

  return grantedNames.isEmpty() ? null : grantedNames.toArray(new GeneralName[0]);
}
 
Example 15
Source File: ExtensionsChecker.java    From xipki with Apache License 2.0 4 votes vote down vote up
private void checkExtnCrlDistributionPoints(StringBuilder failureMsg,
    byte[] extensionValue, IssuerInfo issuerInfo) {
  CRLDistPoint isCrlDistPoints = CRLDistPoint.getInstance(extensionValue);
  DistributionPoint[] isDistributionPoints = isCrlDistPoints.getDistributionPoints();
  if (isDistributionPoints == null) {
    addViolation(failureMsg, "size of CRLDistributionPoints", 0, 1);
    return;
  } else {
    int len = isDistributionPoints.length;
    if (len != 1) {
      addViolation(failureMsg, "size of CRLDistributionPoints", len, 1);
      return;
    }
  }

  Set<String> isCrlUrls = new HashSet<>();
  for (DistributionPoint entry : isDistributionPoints) {
    int asn1Type = entry.getDistributionPoint().getType();
    if (asn1Type != DistributionPointName.FULL_NAME) {
      addViolation(failureMsg, "tag of DistributionPointName of CRLDistibutionPoints",
          asn1Type, DistributionPointName.FULL_NAME);
      continue;
    }

    GeneralNames isDistributionPointNames =
        GeneralNames.getInstance(entry.getDistributionPoint().getName());
    GeneralName[] names = isDistributionPointNames.getNames();

    for (int i = 0; i < names.length; i++) {
      GeneralName name = names[i];
      if (name.getTagNo() != GeneralName.uniformResourceIdentifier) {
        addViolation(failureMsg, "tag of CRL URL", name.getTagNo(),
            GeneralName.uniformResourceIdentifier);
      } else {
        String uri = ((ASN1String) name.getName()).getString();
        isCrlUrls.add(uri);
      }
    }

    Set<String> expCrlUrls = issuerInfo.getCrlUrls();
    Set<String> diffs = strInBnotInA(expCrlUrls, isCrlUrls);
    if (CollectionUtil.isNotEmpty(diffs)) {
      failureMsg.append("CRL URLs ").append(diffs).append(" are present but not expected; ");
    }

    diffs = strInBnotInA(isCrlUrls, expCrlUrls);
    if (CollectionUtil.isNotEmpty(diffs)) {
      failureMsg.append("CRL URLs ").append(diffs).append(" are absent but are required; ");
    }
  }
}
 
Example 16
Source File: ExtensionsChecker.java    From xipki with Apache License 2.0 4 votes vote down vote up
private void checkExtnDeltaCrlDistributionPoints(StringBuilder failureMsg,
    byte[] extensionValue, IssuerInfo issuerInfo) {
  CRLDistPoint isCrlDistPoints = CRLDistPoint.getInstance(extensionValue);
  DistributionPoint[] isDistributionPoints = isCrlDistPoints.getDistributionPoints();
  if (isDistributionPoints == null) {
    addViolation(failureMsg, "size of CRLDistributionPoints (deltaCRL)", 0, 1);
    return;
  } else {
    int len = isDistributionPoints.length;
    if (len != 1) {
      addViolation(failureMsg, "size of CRLDistributionPoints (deltaCRL)", len, 1);
      return;
    }
  }

  Set<String> isCrlUrls = new HashSet<>();
  for (DistributionPoint entry : isDistributionPoints) {
    int asn1Type = entry.getDistributionPoint().getType();
    if (asn1Type != DistributionPointName.FULL_NAME) {
      addViolation(failureMsg, "tag of DistributionPointName of CRLDistibutionPoints (deltaCRL)",
          asn1Type, DistributionPointName.FULL_NAME);
      continue;
    }

    GeneralNames isDistributionPointNames =
        GeneralNames.getInstance(entry.getDistributionPoint().getName());
    GeneralName[] names = isDistributionPointNames.getNames();

    for (int i = 0; i < names.length; i++) {
      GeneralName name = names[i];
      if (name.getTagNo() != GeneralName.uniformResourceIdentifier) {
        addViolation(failureMsg, "tag of deltaCRL URL", name.getTagNo(),
            GeneralName.uniformResourceIdentifier);
      } else {
        String uri = ((ASN1String) name.getName()).getString();
        isCrlUrls.add(uri);
      }
    }

    Set<String> expCrlUrls = issuerInfo.getCrlUrls();
    Set<String> diffs = strInBnotInA(expCrlUrls, isCrlUrls);
    if (CollectionUtil.isNotEmpty(diffs)) {
      failureMsg.append("deltaCRL URLs ").append(diffs).append(" are present but not expected; ");
    }

    diffs = strInBnotInA(isCrlUrls, expCrlUrls);
    if (CollectionUtil.isNotEmpty(diffs)) {
      failureMsg.append("deltaCRL URLs ").append(diffs).append(" are absent but are required; ");
    }
  }
}