org.bouncycastle.asn1.ASN1String Java Examples

The following examples show how to use org.bouncycastle.asn1.ASN1String. 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: 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 #2
Source File: ExtensionSyntaxChecker.java    From xipki with Apache License 2.0 6 votes vote down vote up
private static void checkContentTextOrSubFields(String name, ExtnSyntax subField,
    ASN1Encodable obj) throws BadCertTemplateException {
  if (obj instanceof ASN1String) {
    if (subField.getStringRegex() != null) {
      assertMatch(name, subField.getStringRegex(), ((ASN1String) obj).getString());
    }
    return;
  }

  FieldType syntaxType = subField.type();
  if (syntaxType == FieldType.SEQUENCE) {
    checkSequenceSyntax(name, (ASN1Sequence) obj, subField.getSubFields());
  } else if (syntaxType == FieldType.SET) {
    checkSetSyntax(name, (ASN1Set) obj, subField.getSubFields());
  } else if (syntaxType == FieldType.SEQUENCE_OF) {
    checkSequenceOfOrSetOfSyntax(name, (ASN1Sequence) obj, null, subField.getSubFields());
  } else if (syntaxType == FieldType.SET_OF) {
    checkSequenceOfOrSetOfSyntax(name, null, (ASN1Set) obj, subField.getSubFields());
  }
}
 
Example #3
Source File: CmpUtil.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static CmpUtf8Pairs extract(AttributeTypeAndValue[] atvs) {
  if (atvs != null) {
    for (AttributeTypeAndValue atv : atvs) {
      if (CMPObjectIdentifiers.regInfo_utf8Pairs.equals(atv.getType())) {
        String regInfoValue = ((ASN1String) atv.getValue()).getString();
        return new CmpUtf8Pairs(regInfoValue);
      }
    }
  }

  return null;
}
 
Example #4
Source File: CaUtil.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static String getChallengePassword(CertificationRequestInfo csr) {
  Args.notNull(csr, "csr");
  ASN1Set attrs = csr.getAttributes();
  for (int i = 0; i < attrs.size(); i++) {
    Attribute attr = Attribute.getInstance(attrs.getObjectAt(i));
    if (PKCSObjectIdentifiers.pkcs_9_at_challengePassword.equals(attr.getAttrType())) {
      ASN1String str = (ASN1String) attr.getAttributeValues()[0];
      return str.getString();
    }
  }
  return null;
}
 
Example #5
Source File: ProxyMessage.java    From xipki with Apache License 2.0 5 votes vote down vote up
private RemoveObjectsParams(ASN1Sequence seq) throws BadAsn1ObjectException {
  requireRange(seq, 2, 3);
  int idx = 0;
  slotId = SlotIdentifier.getInstance(seq.getObjectAt(idx++)).getValue();
  final int size = seq.size();
  ASN1Encodable asn1Id = null;
  ASN1Encodable asn1Label = null;
  if (size == 2) {
    ASN1Encodable asn1 = seq.getObjectAt(1);
    if (asn1 instanceof ASN1String) {
      asn1Label = asn1;
    } else {
      asn1Id = asn1;
    }
  } else {
    asn1Id = seq.getObjectAt(idx++);
    asn1Label = seq.getObjectAt(idx++);
  }

  objectId = (asn1Id == null) ? null : getOctetStringBytes(asn1Id);
  objectLabel = (asn1Label == null) ? null : getUtf8String(seq.getObjectAt(idx++));

  if ((objectId == null || objectId.length == 0) && StringUtil.isBlank(objectLabel)) {
    throw new BadAsn1ObjectException("invalid object RemoveObjectsParams: "
        + "at least one of id and label must not be null");
  }
}
 
Example #6
Source File: ScepResponder.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static String getChallengePassword(CertificationRequestInfo csr) {
  ASN1Set attrs = csr.getAttributes();
  for (int i = 0; i < attrs.size(); i++) {
    Attribute attr = Attribute.getInstance(attrs.getObjectAt(i));
    if (PKCSObjectIdentifiers.pkcs_9_at_challengePassword.equals(attr.getAttrType())) {
      ASN1String str = (ASN1String) attr.getAttributeValues()[0];
      return str.getString();
    }
  }
  return null;
}
 
Example #7
Source File: BaseCertprofile.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static RDN createPostalAddressRdn(ASN1ObjectIdentifier type, ASN1Encodable rdnValue,
    RdnControl control, int index) throws BadCertTemplateException {
  Args.notNull(type, "type");

  if (!(rdnValue instanceof ASN1Sequence)) {
    throw new BadCertTemplateException("rdnValue of RDN postalAddress has incorrect syntax");
  }

  ASN1Sequence seq = (ASN1Sequence) rdnValue;
  final int size = seq.size();
  if (size < 1 || size > 6) {
    throw new BadCertTemplateException(
        "Sequence size of RDN postalAddress is not within [1, 6]: " + size);
  }

  ASN1EncodableVector vec = new ASN1EncodableVector();
  for (int i = 0; i < size; i++) {
    ASN1Encodable line = seq.getObjectAt(i);
    String text;
    if (line instanceof ASN1String && !(line instanceof DERUniversalString)) {
      text = ((ASN1String) line).getString();
    } else {
      throw new BadCertTemplateException(
        String.format("postalAddress[%d] has incorrect syntax", i));
    }

    ASN1Encodable asn1Line = createRdnValue(text, type, control, index);
    vec.add(asn1Line);
  }

  return new RDN(type, new DERSequence(vec));
}
 
Example #8
Source File: CmpUtil.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static CmpUtf8Pairs extract(InfoTypeAndValue[] regInfos) {
  if (regInfos != null) {
    for (InfoTypeAndValue regInfo : regInfos) {
      if (CMPObjectIdentifiers.regInfo_utf8Pairs.equals(regInfo.getInfoType())) {
        String regInfoValue = ((ASN1String) regInfo.getInfoValue()).getString();
        return new CmpUtf8Pairs(regInfoValue);
      }
    }
  }

  return null;
}
 
Example #9
Source File: X509Util.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static String rdnValueToString(ASN1Encodable value) {
  Args.notNull(value, "value");
  if (value instanceof ASN1String && !(value instanceof DERUniversalString)) {
    return ((ASN1String) value).getString();
  } else {
    try {
      return "#" + Hex.encode(
          value.toASN1Primitive().getEncoded(ASN1Encoding.DER));
    } catch (IOException ex) {
      throw new IllegalArgumentException("other value has no encoded form");
    }
  }
}
 
Example #10
Source File: DSSASN1Utils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static String getString(ASN1Encodable attributeValue) {
	String string;
	if (attributeValue instanceof ASN1String) {
		string = ((ASN1String) attributeValue).getString();
	} else if (attributeValue instanceof ASN1ObjectIdentifier) {
		string = ((ASN1ObjectIdentifier) attributeValue).getId();
	} else {
		LOG.error("!!!*******!!! This encoding is unknown: {}", attributeValue.getClass().getSimpleName());
		string = attributeValue.toString();
		LOG.error("!!!*******!!! value: {}", string);
	}
	return string;
}
 
Example #11
Source File: DSSASN1Utils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static String parseGn(GeneralName gn) {
	try {
		if (GeneralName.uniformResourceIdentifier == gn.getTagNo()) {
			ASN1String str = (ASN1String) ((DERTaggedObject) gn.toASN1Primitive()).getObject();
			return str.getString();
		}
	} catch (Exception e) {
		LOG.warn("Unable to parse GN '{}'", gn, e);
	}
	return null;
}
 
Example #12
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 #13
Source File: CAdESSignature.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public List<SignerRole> getClaimedSignerRoles() {
	final SignerAttribute signerAttr = getSignerAttributeV1();
	final SignerAttributeV2 signerAttrV2 = getSignerAttributeV2();

	Object[] signerAttrValues = null;
	try {

		if (signerAttr != null) {
			signerAttrValues = signerAttr.getValues();
		} else if (signerAttrV2 != null) {
			signerAttrValues = signerAttrV2.getValues();
		}
		if (signerAttrValues == null) {
			return Collections.emptyList();
		}

		final List<SignerRole> claimedRoles = new ArrayList<>();
		for (final Object signerAttrValue : signerAttrValues) {
			if (!(signerAttrValue instanceof org.bouncycastle.asn1.x509.Attribute[])) {
				continue;
			}
			final org.bouncycastle.asn1.x509.Attribute[] signerAttrValueArray = (org.bouncycastle.asn1.x509.Attribute[]) signerAttrValue;
			for (final org.bouncycastle.asn1.x509.Attribute claimedRole : signerAttrValueArray) {
				final ASN1Encodable[] attrValues1 = claimedRole.getAttrValues().toArray();
				for (final ASN1Encodable asn1Encodable : attrValues1) {
					if (asn1Encodable instanceof ASN1String) {
						ASN1String asn1String = (ASN1String) asn1Encodable;
						final String role = asn1String.getString();
						claimedRoles.add(new SignerRole(role, EndorsementType.CLAIMED));
					}
				}
			}
		}
		return claimedRoles;
	} catch (Exception e) {
		LOG.error("Error when dealing with claimed signer roles : {}", signerAttrValues, e);
		return Collections.emptyList();
	}
}
 
Example #14
Source File: Asn1Dump.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
private String dumpString(ASN1String asn1String) {
	StringBuilder sb = new StringBuilder();

	sb.append(indentSequence.toString(indentLevel));

	if (asn1String instanceof DERBMPString) {
		sb.append("BMP STRING=");
	} else if (asn1String instanceof DERGeneralString) {
		sb.append("GENERAL STRING=");
	} else if (asn1String instanceof DERIA5String) {
		sb.append("IA5 STRING=");
	} else if (asn1String instanceof DERNumericString) {
		sb.append("NUMERIC STRING=");
	} else if (asn1String instanceof DERPrintableString) {
		sb.append("PRINTABLE STRING=");
	} else if (asn1String instanceof DERT61String) {
		sb.append("TELETEX STRING=");
	} else if (asn1String instanceof DERUniversalString) {
		sb.append("UNIVERSAL STRING=");
	} else if (asn1String instanceof DERUTF8String) {
		sb.append("UTF8 STRING=");
	} else if (asn1String instanceof DERVisibleString) {
		sb.append("VISIBLE STRING=");
	} else {
		sb.append("UNKNOWN STRING=");
	}

	sb.append("'");
	sb.append(asn1String.getString());
	sb.append("'");
	sb.append(NEWLINE);

	return sb.toString();
}
 
Example #15
Source File: Asn1Dump.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get dump of the supplied ASN.1 object.
 *
 * @param asn1Object
 *            ASN.1 object
 * @return Dump of object
 * @throws Asn1Exception
 *             A problem was encountered getting the ASN.1 dump
 * @throws IOException
 *             If an I/O problem occurred
 */
public String dump(ASN1Primitive asn1Object) throws Asn1Exception, IOException {
	// Get dump of the supplied ASN.1 object incrementing the indent level of the output
	try {
		indentLevel++;

		if (asn1Object instanceof DERBitString) { // special case of ASN1String
			return dumpBitString((DERBitString) asn1Object);
		} else if (asn1Object instanceof ASN1String) {
			return dumpString((ASN1String) asn1Object);
		} else if (asn1Object instanceof ASN1UTCTime) {
			return dumpUTCTime((ASN1UTCTime) asn1Object);
		} else if (asn1Object instanceof ASN1GeneralizedTime) {
			return dumpGeneralizedTime((ASN1GeneralizedTime) asn1Object);
		} else if (asn1Object instanceof ASN1Sequence ||
				asn1Object instanceof ASN1Set ) {
			return dumpSetOrSequence(asn1Object);
		} else if (asn1Object instanceof ASN1TaggedObject) {
			return dumpTaggedObject((ASN1TaggedObject) asn1Object);
		} else if (asn1Object instanceof ASN1Boolean) {
			return dumpBoolean((ASN1Boolean) asn1Object);
		} else if (asn1Object instanceof ASN1Enumerated) {
			return dumpEnumerated((ASN1Enumerated) asn1Object);
		} else if (asn1Object instanceof ASN1Integer) {
			return dumpInteger((ASN1Integer) asn1Object);
		} else if (asn1Object instanceof ASN1Null) {
			return dumpNull();
		} else if (asn1Object instanceof ASN1ObjectIdentifier) {
			return dumpObjectIdentifier((ASN1ObjectIdentifier) asn1Object);
		} else if (asn1Object instanceof ASN1OctetString) {
			return dumpOctetString((ASN1OctetString) asn1Object);
		} else {
			throw new Asn1Exception("Unknown ASN.1 object: " + asn1Object.toString());
		}
	} finally {
		indentLevel--;
	}
}
 
Example #16
Source File: X509Ext.java    From portecle with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Get Novell Security Attributes (2.16.840.1.113719.1.9.4.1) extension value as a string.
 *
 * @see <a href="https://www.novell.com/documentation/developer/ncslib/npki_enu/data/a2uetmm.html">Novell Security
 *      Attributes Extension</a>
 * @param bValue The octet string value
 * @return Extension value as a string
 * @throws IOException If an I/O problem occurs
 */
private String getNovellSecurityAttributesStringValue(byte[] bValue)
    throws IOException
{
	// TODO...

	ASN1Sequence attrs = (ASN1Sequence) ASN1Primitive.fromByteArray(bValue);
	StringBuilder sb = new StringBuilder();

	// "Novell Security Attribute(tm)"
	String sTM = ((ASN1String) attrs.getObjectAt(2)).getString();
	sb.append(escapeHtml(sTM));
	sb.append("<br>");

	// OCTET STRING of size 2, 1st is major version, 2nd is minor version
	byte[] bVer = ((DEROctetString) attrs.getObjectAt(0)).getOctets();
	sb.append("Major version: ").append(Byte.toString(bVer[0]));
	sb.append(", minor version: ").append(Byte.toString(bVer[1]));
	sb.append("<br>");

	// Nonverified Subscriber Information
	boolean bNSI = ((ASN1Boolean) attrs.getObjectAt(1)).isTrue();
	sb.append("Nonverified Subscriber Information: ").append(bNSI);
	sb.append("<br>");

	// URI reference
	String sUri = ((ASN1String) attrs.getObjectAt(3)).getString();
	sb.append("URI: ");
	sb.append(getLink(sUri, escapeHtml(sUri), LinkClass.BROWSER));

	// GLB Extensions (GLB ~ "Greatest Lower Bound")

	sb.append("<ul>");
	ASN1Sequence glbs = (ASN1Sequence) attrs.getObjectAt(4);
	sb.append("<li>GLB extensions:<ul>");

	/*
	 * TODO: verify that we can do getObjectAt(n) or if we need to examine tag numbers of the tagged objects
	 */

	// Key quality
	ASN1Sequence keyq = (ASN1Sequence) ((ASN1TaggedObject) glbs.getObjectAt(0)).getObject();
	sb.append("<li>").append(RB.getString("NovellKeyQuality"));
	sb.append("<ul>").append(getNovellQualityAttr(keyq)).append("</ul></li>");

	// Crypto process quality
	ASN1Sequence cpq = (ASN1Sequence) ((ASN1TaggedObject) glbs.getObjectAt(1)).getObject();
	sb.append("<li>").append(RB.getString("NovellCryptoProcessQuality"));
	sb.append("<ul>").append(getNovellQualityAttr(cpq)).append("</ul></li>");

	// Certificate class
	ASN1Sequence cclass = (ASN1Sequence) ((ASN1TaggedObject) glbs.getObjectAt(2)).getObject();
	sb.append("<li>").append(RB.getString("NovellCertClass"));
	sb.append(": ");
	BigInteger sv = ((ASN1Integer) cclass.getObjectAt(0)).getValue();
	String sc = getRes("NovellCertClass." + sv, "UnregocnisedNovellCertClass");
	sb.append(MessageFormat.format(sc, sv));
	sb.append("</li>");

	boolean valid = true;
	if (cclass.size() > 1)
	{
		valid = ((ASN1Boolean) cclass.getObjectAt(1)).isTrue();
	}
	sb.append("<li>");
	sb.append(RB.getString("NovellCertClassValid." + valid));
	sb.append("</li></ul>");

	// Enterprise ID
	/*
	 * ASN1Sequence eid = (ASN1Sequence) ((ASN1TaggedObject) glbs.getObjectAt(3)).getObject(); ASN1Sequence
	 * rootLabel = (ASN1Sequence) ((ASN1TaggedObject) eid.getObjectAt(0)).getObject(); ASN1Sequence registryLabel =
	 * (ASN1Sequence) ((ASN1TaggedObject) eid.getObjectAt(1)).getObject(); ASN1Sequence eLabels = (ASN1Sequence)
	 * ((ASN1TaggedObject) eid.getObjectAt(2)).getObject(); for (int i = 0, len = eLabels.size(); i < len; i++) { //
	 * Hmm... I thought this would be a sequence of sequences, // but the following throws a ClassCastException...?
	 * // ASN1Sequence eLabel = (ASN1Sequence) eLabels.getObjectAt(i); }
	 */
	sb.append(RB.getString("NovellEnterpriseID"));
	sb.append(' ').append(RB.getString("DecodeNotImplemented")); // TODO

	return sb.toString();
}
 
Example #17
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 #18
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; ");
    }
  }
}
 
Example #19
Source File: ExtensionsChecker.java    From xipki with Apache License 2.0 4 votes vote down vote up
private void checkDirectoryString(ASN1ObjectIdentifier extnType,
    DirectoryStringType type, String text,
    StringBuilder failureMsg, byte[] extensionValue, Extensions requestedExtns,
    ExtensionControl extControl) {
  if (type == null) {
    checkConstantExtnValue(extnType, failureMsg, extensionValue, requestedExtns, extControl);
    return;
  }

  ASN1Primitive asn1;
  try {
    asn1 = ASN1Primitive.fromByteArray(extensionValue);
  } catch (IOException ex) {
    failureMsg.append("invalid syntax of extension value; ");
    return;
  }

  boolean correctStringType;

  switch (type) {
    case bmpString:
      correctStringType = (asn1 instanceof DERBMPString);
      break;
    case printableString:
      correctStringType = (asn1 instanceof DERPrintableString);
      break;
    case teletexString:
      correctStringType = (asn1 instanceof DERT61String);
      break;
    case utf8String:
      correctStringType = (asn1 instanceof DERUTF8String);
      break;
    default:
      throw new IllegalStateException("should not reach here, unknown DirectoryStringType "
          + type);
  } // end switch

  if (!correctStringType) {
    failureMsg.append("extension value is not of type DirectoryString.")
      .append(text).append("; ");
    return;
  }

  String extTextValue = ((ASN1String) asn1).getString();
  if (!text.equals(extTextValue)) {
    addViolation(failureMsg, "content", extTextValue, text);
  }
}
 
Example #20
Source File: ExtensionsChecker.java    From xipki with Apache License 2.0 4 votes vote down vote up
private static void checkAia(StringBuilder failureMsg, AuthorityInformationAccess aia,
    ASN1ObjectIdentifier accessMethod, Set<String> expectedUris) {
  String typeDesc;
  if (X509ObjectIdentifiers.id_ad_ocsp.equals(accessMethod)) {
    typeDesc = "OCSP";
  } else if (X509ObjectIdentifiers.id_ad_caIssuers.equals(accessMethod)) {
    typeDesc = "caIssuer";
  } else {
    typeDesc = accessMethod.getId();
  }

  List<AccessDescription> isAccessDescriptions = new LinkedList<>();
  for (AccessDescription accessDescription : aia.getAccessDescriptions()) {
    if (accessMethod.equals(accessDescription.getAccessMethod())) {
      isAccessDescriptions.add(accessDescription);
    }
  }

  int size = isAccessDescriptions.size();
  if (size != expectedUris.size()) {
    addViolation(failureMsg, "number of AIA " + typeDesc + " URIs", size, expectedUris.size());
    return;
  }

  Set<String> isUris = new HashSet<>();
  for (int i = 0; i < size; i++) {
    GeneralName isAccessLocation = isAccessDescriptions.get(i).getAccessLocation();
    if (isAccessLocation.getTagNo() != GeneralName.uniformResourceIdentifier) {
      addViolation(failureMsg, "tag of accessLocation of AIA ",
          isAccessLocation.getTagNo(), GeneralName.uniformResourceIdentifier);
    } else {
      String isOcspUri = ((ASN1String) isAccessLocation.getName()).getString();
      isUris.add(isOcspUri);
    }
  }

  Set<String> diffs = strInBnotInA(expectedUris, isUris);
  if (CollectionUtil.isNotEmpty(diffs)) {
    failureMsg.append(typeDesc).append(" URIs ").append(diffs);
    failureMsg.append(" are present but not expected; ");
  }

  diffs = strInBnotInA(isUris, expectedUris);
  if (CollectionUtil.isNotEmpty(diffs)) {
    failureMsg.append(typeDesc).append(" URIs ").append(diffs);
    failureMsg.append(" are absent but are required; ");
  }
}
 
Example #21
Source File: X509Ext.java    From portecle with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Gets a HTML escaped string representation of the given object.
 *
 * @param obj Object
 * @return String representation of <code>obj</code>
 */
private static String stringify(Object obj)
{
	if (obj instanceof ASN1String)
	{
		return escapeHtml(((ASN1String) obj).getString());
	}
	// TODO: why not ASN1Integer as number?
	else if (obj instanceof ASN1Integer || obj instanceof byte[])
	{
		return convertToHexString(obj);
	}
	else if (obj instanceof ASN1TaggedObject)
	{
		ASN1TaggedObject tagObj = (ASN1TaggedObject) obj;
		// Note: "[", _not_ '[' ...
		return "[" + tagObj.getTagNo() + "] " + stringify(tagObj.getObject());
	}
	else if (obj instanceof ASN1Sequence)
	{
		ASN1Sequence aObj = (ASN1Sequence) obj;
		StringBuilder tmp = new StringBuilder("[");
		for (int i = 0, len = aObj.size(); i < len; i++)
		{
			tmp.append(stringify(aObj.getObjectAt(i)));
			if (i != len - 1)
			{
				tmp.append(", ");
			}
		}
		return tmp.append("]").toString();
	}
	else
	{
		String hex = null;
		try
		{
			Method method = obj.getClass().getMethod("getOctets", (Class[]) null);
			hex = convertToHexString(method.invoke(obj, (Object[]) null));
		}
		catch (Exception e)
		{
			// Ignore
		}
		if (hex == null && obj != null)
		{
			hex = escapeHtml(obj.toString());
		}
		return hex;
	}
}