Java Code Examples for org.bouncycastle.asn1.ASN1Set#size()

The following examples show how to use org.bouncycastle.asn1.ASN1Set#size() . 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: CAdESTimestampDataBuilder.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Remove any archive-timestamp-v2/3 attribute added after the
 * timestampToken
 */
private ASN1Sequence filterUnauthenticatedAttributes(ASN1Set unauthenticatedAttributes, TimestampToken timestampToken) {
	ASN1EncodableVector result = new ASN1EncodableVector();
	for (int ii = 0; ii < unauthenticatedAttributes.size(); ii++) {

		final Attribute attribute = Attribute.getInstance(unauthenticatedAttributes.getObjectAt(ii));
		final ASN1ObjectIdentifier attrType = attribute.getAttrType();
		if (id_aa_ets_archiveTimestampV2.equals(attrType) || id_aa_ets_archiveTimestampV3.equals(attrType)) {
			try {

				TimeStampToken token = DSSASN1Utils.getTimeStampToken(attribute);
				if (!token.getTimeStampInfo().getGenTime().before(timestampToken.getGenerationTime())) {
					continue;
				}
			} catch (Exception e) {
				throw new DSSException(e);
			}
		}
		result.add(unauthenticatedAttributes.getObjectAt(ii));
	}
	return new DERSequence(result);
}
 
Example 2
Source File: CMSOCSPSource.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void collectRevocationRefs(AttributeTable unsignedAttributes, ASN1ObjectIdentifier revocationReferencesAttribute, RevocationRefOrigin origin) {
	final Attribute attribute = unsignedAttributes.get(revocationReferencesAttribute);
	if (attribute == null) {
		return;
	}
	final ASN1Set attrValues = attribute.getAttrValues();
	if (attrValues.size() <= 0) {
		return;
	}

	final ASN1Encodable attrValue = attrValues.getObjectAt(0);
	final ASN1Sequence completeRevocationRefs = (ASN1Sequence) attrValue;
	for (int i = 0; i < completeRevocationRefs.size(); i++) {

		final CrlOcspRef otherCertId = CrlOcspRef.getInstance(completeRevocationRefs.getObjectAt(i));
		final OcspListID ocspListID = otherCertId.getOcspids();
		if (ocspListID != null) {
			for (final OcspResponsesID ocspResponsesID : ocspListID.getOcspResponses()) {
				final OCSPRef ocspRef = new OCSPRef(ocspResponsesID);
				addRevocationReference(ocspRef, origin);
			}
		}
	}
}
 
Example 3
Source File: CMSCertificateSource.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void extractSigningCertificateV1(Attribute attribute) {
	final ASN1Set attrValues = attribute.getAttrValues();
	for (int ii = 0; ii < attrValues.size(); ii++) {
		final ASN1Encodable asn1Encodable = attrValues.getObjectAt(ii);
		try {
			final SigningCertificate signingCertificate = SigningCertificate.getInstance(asn1Encodable);
			if (signingCertificate != null) {
				extractESSCertIDs(signingCertificate.getCerts(), CertificateRefOrigin.SIGNING_CERTIFICATE);
			} else {
				LOG.warn("SigningCertificate attribute is null");
			}
		} catch (Exception e) {
			LOG.warn("SigningCertificate attribute '{}' is not well defined!", Utils.toBase64(DSSASN1Utils.getDEREncoded(asn1Encodable)));
		}
	}
}
 
Example 4
Source File: CMSCertificateSource.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void extractSigningCertificateV2(Attribute attribute) {
	final ASN1Set attrValues = attribute.getAttrValues();
	for (int ii = 0; ii < attrValues.size(); ii++) {
		final ASN1Encodable asn1Encodable = attrValues.getObjectAt(ii);
		try {
			final SigningCertificateV2 signingCertificate = SigningCertificateV2.getInstance(asn1Encodable);
			if (signingCertificate != null) {
				extractESSCertIDv2s(signingCertificate.getCerts(), CertificateRefOrigin.SIGNING_CERTIFICATE);
			} else {
				LOG.warn("SigningCertificateV2 attribute is null");
			}
		} catch (Exception e) {
			LOG.warn("SigningCertificateV2 attribute '{}' is not well defined!", Utils.toBase64(DSSASN1Utils.getDEREncoded(asn1Encodable)));
		}
	}
}
 
Example 5
Source File: ExtensionSyntaxChecker.java    From xipki with Apache License 2.0 6 votes vote down vote up
private static void checkSetSyntax(String name, ASN1Set set, List<SubFieldSyntax> subFields)
    throws BadCertTemplateException {
  List<SubFieldSyntax> subFields0 = new ArrayList<SubFieldSyntax>(subFields);

  final int size = set.size();

  for (int i = 0; i < size; i++) {
    ASN1ObjectHolder objHolder = new ASN1ObjectHolder();
    objHolder.object = set.getObjectAt(i);
    // find the matched SubField
    SubFieldSyntax syntax = getSyntax(name, objHolder, subFields0);

    if (syntax == null) {
      throw new BadCertTemplateException("invalid " + name);
    }

    subFields0.remove(syntax);
    checkContentTextOrSubFields(name, syntax, objHolder.object);
  }

  for (SubFieldSyntax m : subFields0) {
    if (m.isRequired()) {
      throw new BadCertTemplateException("invalid " + name);
    }
  }
}
 
Example 6
Source File: CaUtil.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static Extensions getExtensions(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_extensionRequest.equals(attr.getAttrType())) {
      return Extensions.getInstance(attr.getAttributeValues()[0]);
    }
  }
  return null;
}
 
Example 7
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 8
Source File: ScepUtil.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static ASN1Encodable getFirstAttrValue(AttributeTable attrs, ASN1ObjectIdentifier type) {
  Args.notNull(attrs, "attrs");
  Args.notNull(type, "type");
  Attribute attr = attrs.get(type);
  if (attr == null) {
    return null;
  }
  ASN1Set set = attr.getAttrValues();
  return (set.size() == 0) ? null : set.getObjectAt(0);
}
 
Example 9
Source File: ScepUtil.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static X509CRLHolder getCrlFromPkiMessage(SignedData signedData) throws CRLException {
  Args.notNull(signedData, "signedData");
  ASN1Set set = signedData.getCRLs();
  if (set == null || set.size() == 0) {
    return null;
  }

  try {
    CertificateList cl = CertificateList.getInstance(set.getObjectAt(0));
    return new X509CRLHolder(cl);
  } catch (IllegalArgumentException ex) {
    throw new CRLException(ex);
  }
}
 
Example 10
Source File: ScepUtil.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static List<X509Cert> getCertsFromSignedData(SignedData signedData)
    throws CertificateException {
  Args.notNull(signedData, "signedData");
  ASN1Set set = signedData.getCertificates();
  if (set == null) {
    return Collections.emptyList();
  }

  final int n = set.size();
  if (n == 0) {
    return Collections.emptyList();
  }

  List<X509Cert> certs = new LinkedList<>();

  X509Cert eeCert = null;
  for (int i = 0; i < n; i++) {
    X509Cert cert;
    try {
      cert = new X509Cert(Certificate.getInstance(set.getObjectAt(i)));
    } catch (IllegalArgumentException ex) {
      throw new CertificateException(ex);
    }

    if (eeCert == null && cert.getBasicConstraints() == -1) {
      eeCert = cert;
    } else {
      certs.add(cert);
    }
  }

  if (eeCert != null) {
    certs.add(0, eeCert);
  }

  return certs;
}
 
Example 11
Source File: EnrolmentResponse.java    From xipki with Apache License 2.0 5 votes vote down vote up
public EnrolmentResponse(PkiMessage pkcsRep) throws ScepClientException {
  Args.notNull(pkcsRep, "pkcsRep");
  MessageType messageType = pkcsRep.getMessageType();
  if (MessageType.CertRep != messageType) {
    throw new ScepClientException("messageType must not be other than CertRep: " + messageType);
  }
  this.pkcsRep = pkcsRep;

  if (PkiStatus.SUCCESS != pkcsRep.getPkiStatus()) {
    return;
  }

  ASN1Encodable messageData = pkcsRep.getMessageData();
  if (!(messageData instanceof ContentInfo)) {
    throw new ScepClientException("pkcsRep is not a ContentInfo");
  }

  ContentInfo ci = (ContentInfo) messageData;
  SignedData sd = SignedData.getInstance(ci.getContent());
  ASN1Set asn1Certs = sd.getCertificates();
  if (asn1Certs == null || asn1Certs.size() == 0) {
    throw new ScepClientException("no certificate is embedded in pkcsRep");
  }

  try {
    this.certificates = Collections.unmodifiableList(ScepUtil.getCertsFromSignedData(sd));
  } catch (CertificateException ex) {
    throw new ScepClientException(ex.getMessage(), ex);
  }
}
 
Example 12
Source File: ExtensionSyntaxChecker.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static void checkSequenceOfOrSetOfSyntax(String name, ASN1Sequence seq,
    ASN1Set set, List<SubFieldSyntax> subFields) throws BadCertTemplateException {
  final int size = (seq != null) ? seq.size() : set.size();

  for (int i = 0; i < size; i++) {
    ASN1ObjectHolder objHolder = new ASN1ObjectHolder();
    objHolder.object = (seq != null) ? seq.getObjectAt(i) : set.getObjectAt(i);
    SubFieldSyntax subField = getSyntax(name, objHolder, subFields);
    if (subField == null) {
      throw new BadCertTemplateException("invalid " + name);
    }
    checkField(name, objHolder.object, subField);
  }
}
 
Example 13
Source File: DSSASN1Utils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Returns {@link ASN1Encodable} for a given {@code oid} found in the {@code unsignedAttributes}
 * @param unsignedAttributes {@link AttributeTable} of a signature
 * @param oid target {@link ASN1ObjectIdentifier}
 * @return {@link ASN1Encodable}
 */
public static ASN1Encodable getAsn1Encodable(AttributeTable unsignedAttributes, ASN1ObjectIdentifier oid) {
	final ASN1Set attrValues = getAsn1AttributeSet(unsignedAttributes, oid);
	if (attrValues == null || attrValues.size() <= 0) {
		return null;
	}
	return attrValues.getObjectAt(0);
}
 
Example 14
Source File: DSSASN1Utils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Returns ats-hash-index table, with a specified version present in from timestamp's unsigned properties
 * 
 * @param timestampUnsignedAttributes {@link AttributeTable} unsigned properties of the timestamp
 * @param atsHashIndexVersionIdentifier {@link ASN1ObjectIdentifier} identifier of ats-hash-index table to get
 * @return the content of SignedAttribute: ATS-hash-index unsigned attribute with a requested version if present
 */
public static ASN1Sequence getAtsHashIndexByVersion(AttributeTable timestampUnsignedAttributes, 
		ASN1ObjectIdentifier atsHashIndexVersionIdentifier) {
	if (timestampUnsignedAttributes != null && atsHashIndexVersionIdentifier != null) {
		final Attribute atsHashIndexAttribute = timestampUnsignedAttributes.get(atsHashIndexVersionIdentifier);
		if (atsHashIndexAttribute != null) {
			final ASN1Set attrValues = atsHashIndexAttribute.getAttrValues();
			if (attrValues != null && attrValues.size() == 1) {
				return (ASN1Sequence) attrValues.getObjectAt(0).toASN1Primitive();
			}
		}
	}
	return null;
}
 
Example 15
Source File: InfiniteLoopDSS621Test.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private List<X509Certificate> extractCertificates(SignedData signedData) throws Exception {
	ASN1Set certificates = signedData.getCertificates();
	logger.debug("CERTIFICATES (" + certificates.size() + ") : " + certificates);

	List<X509Certificate> foundCertificates = new ArrayList<>();
	for (int i = 0; i < certificates.size(); i++) {
		ASN1Sequence seqCertif = ASN1Sequence.getInstance(certificates.getObjectAt(i));

		X509CertificateHolder certificateHolder = new X509CertificateHolder(seqCertif.getEncoded());
		CertificateToken certificate = DSSASN1Utils.getCertificate(certificateHolder);

		foundCertificates.add(certificate.getCertificate());
	}
	return foundCertificates;
}
 
Example 16
Source File: AbstractRequirementChecks.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private int countInSet(ASN1ObjectIdentifier oid, ASN1Set set) {
	int counter = 0;
	if (set != null) {
		for (int i = 0; i < set.size(); i++) {
			ASN1Sequence attrSeq = ASN1Sequence.getInstance(set.getObjectAt(i));
			ASN1ObjectIdentifier attrOid = ASN1ObjectIdentifier.getInstance(attrSeq.getObjectAt(0));
			if (oid.equals(attrOid)) {
				counter++;
			}
		}
	}
	return counter;
}
 
Example 17
Source File: AbstractRequirementChecks.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * SignedData.certificates shall be present in B/T/LT/LTA
 */
@Test
public void checkSignedDataCertificatesPresent() throws Exception {
	ASN1Set certificates = signedData.getCertificates();
	logger.info("CERTIFICATES (" + certificates.size() + ") : " + certificates);

	for (int i = 0; i < certificates.size(); i++) {
		ASN1Sequence seqCertif = ASN1Sequence.getInstance(certificates.getObjectAt(i));
		X509CertificateHolder certificateHolder = new X509CertificateHolder(seqCertif.getEncoded());
		CertificateToken certificate = DSSASN1Utils.getCertificate(certificateHolder);
		certificate.getCertificate().checkValidity();
	}
}
 
Example 18
Source File: CAdESWithContentTimestampTest.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected DSSDocument getSignedDocument() {
	FileDocument fileDocument = new FileDocument("src/test/resources/validation/Signature-C-BES-4.p7m");
	
	try (InputStream is = fileDocument.openStream(); ASN1InputStream asn1sInput = new ASN1InputStream(is)) {
		ASN1Sequence asn1Seq = (ASN1Sequence) asn1sInput.readObject();

		ASN1TaggedObject taggedObj = ASN1TaggedObject.getInstance(asn1Seq.getObjectAt(1));
		ASN1Primitive object = taggedObj.getObject();
		SignedData signedData = SignedData.getInstance(object);

		ASN1Set signerInfosAsn1 = signedData.getSignerInfos();
		ASN1Sequence seqSignedInfo = ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0));

		SignerInfo signedInfo = SignerInfo.getInstance(seqSignedInfo);
		ASN1Set authenticatedAttributes = signedInfo.getAuthenticatedAttributes();

		boolean found = false;
		for (int i = 0; i < authenticatedAttributes.size(); i++) {
			ASN1Sequence authAttrSeq = ASN1Sequence.getInstance(authenticatedAttributes.getObjectAt(i));
			ASN1ObjectIdentifier attrOid = ASN1ObjectIdentifier.getInstance(authAttrSeq.getObjectAt(0));
			if (PKCSObjectIdentifiers.id_aa_ets_contentTimestamp.equals(attrOid)) {
				found = true;
			}
		}
		assertTrue(found);
	} catch (Exception e) {
		fail(e);
	}
	
	return fileDocument;
}
 
Example 19
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 20
Source File: CertificateAuthority.java    From DeviceConnect-Android with MIT License 4 votes vote down vote up
/**
 * 証明書署名要求から Subject Alternative Names (SANs) を取得する.
 *
 * @param request 証明書署名要求
 * @return SubjectAlternativeNamesを示す {@link GeneralNames} オブジェクト
 * @throws IOException 解析に失敗した場合
 */
private GeneralNames parseSANs(final PKCS10CertificationRequest request) throws IOException {
    List<ASN1Encodable> generalNames = new ArrayList<>();

    CertificationRequestInfo info = request.getCertificationRequestInfo();
    ASN1Set attributes = info.getAttributes();
    for (int i = 0; i < attributes.size(); i++) {
        DEREncodable extensionRequestObj = attributes.getObjectAt(i);
        if (!(extensionRequestObj instanceof DERSequence)) {
            continue;
        }
        DERSequence extensionRequest = (DERSequence) extensionRequestObj;
        if (extensionRequest.size() != 2) {
            continue;
        }
        DEREncodable idObj = extensionRequest.getObjectAt(0);
        DEREncodable contentObj = extensionRequest.getObjectAt(1);
        if (!(idObj instanceof ASN1ObjectIdentifier && contentObj instanceof DERSet)) {
            continue;
        }
        ASN1ObjectIdentifier id = (ASN1ObjectIdentifier) idObj;
        DERSet content = (DERSet) contentObj;
        if (!id.getId().equals("1.2.840.113549.1.9.14")) {
            continue;
        }
        if (content.size() < 1) {
            continue;
        }
        DEREncodable extensionsObj = content.getObjectAt(0);
        if (!(extensionsObj instanceof DERSequence)) {
            continue;
        }
        DERSequence extensions = (DERSequence) extensionsObj;

        for (int k = 0; k < extensions.size(); k++) {
            DEREncodable extensionObj = extensions.getObjectAt(k);
            if (!(extensionObj instanceof DERSequence)) {
                continue;
            }
            DERSequence extension = (DERSequence) extensionObj;
            if (extension.size() != 2) {
                continue;
            }
            DEREncodable extensionIdObj = extension.getObjectAt(0);
            DEREncodable extensionContentObj = extension.getObjectAt(1);
            if (!(extensionIdObj instanceof ASN1ObjectIdentifier)) {
                continue;
            }
            ASN1ObjectIdentifier extensionId = (ASN1ObjectIdentifier) extensionIdObj;
            if (extensionId.getId().equals("2.5.29.17")) {
                DEROctetString san = (DEROctetString) extensionContentObj;

                ASN1StreamParser sanParser = new ASN1StreamParser(san.parser().getOctetStream());
                DEREncodable namesObj = sanParser.readObject().getDERObject();
                if (namesObj instanceof DERSequence) {
                    DERSequence names = (DERSequence) namesObj;
                    for (int m = 0; m < names.size(); m++) {
                        DEREncodable nameObj = names.getObjectAt(m);
                        if (nameObj instanceof DERTaggedObject) {
                            DERTaggedObject name = (DERTaggedObject) nameObj;
                            switch (name.getTagNo()) {
                                case GeneralName.dNSName:
                                    generalNames.add(new GeneralName(GeneralName.dNSName, DERIA5String.getInstance(name, false)));
                                    break;
                                case GeneralName.iPAddress:
                                    generalNames.add(new GeneralName(GeneralName.iPAddress, DEROctetString.getInstance(name, true)));
                                    break;
                            }
                        }
                    }
                }
            }
        }
    }
    if (generalNames.size() > 0) {
        return new GeneralNames(new DERSequence(generalNames.toArray(new ASN1Encodable[0])));
    }
    return null;
}