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

The following examples show how to use org.bouncycastle.asn1.ASN1Set#getObjectAt() . 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: CAdESSignature.java    From dss with GNU Lesser General Public License v2.1 7 votes vote down vote up
private SignerAttribute getSignerAttributeV1() {
	final Attribute id_aa_ets_signerAttr = getSignedAttribute(PKCSObjectIdentifiers.id_aa_ets_signerAttr);
	if (id_aa_ets_signerAttr != null) {
		final ASN1Set attrValues = id_aa_ets_signerAttr.getAttrValues();
		final ASN1Encodable attrValue = attrValues.getObjectAt(0);
		try {
			return SignerAttribute.getInstance(attrValue);
		} catch (Exception e) {
			String warningMessage = "Unable to parse signerAttr - [{}]. Reason : {}";
			if (LOG.isDebugEnabled()) {
				LOG.warn(warningMessage, Utils.toBase64(DSSASN1Utils.getDEREncoded(attrValue)), e.getMessage(), e);
			} else {
				LOG.warn(warningMessage, Utils.toBase64(DSSASN1Utils.getDEREncoded(attrValue)), e.getMessage());
			}
		}
	}
	return null;
}
 
Example 2
Source File: CertificateUtils.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Extract extensions from CSR object
 */
public static Extensions getExtensionsFromCSR(JcaPKCS10CertificationRequest csr) {
    Attribute[] attributess = csr.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    for (Attribute attribute : attributess) {
        ASN1Set attValue = attribute.getAttrValues();
        if (attValue != null) {
            ASN1Encodable extension = attValue.getObjectAt(0);
            if (extension instanceof Extensions) {
                return (Extensions) extension;
            } else if (extension instanceof DERSequence) {
                return Extensions.getInstance(extension);
            }
        }
    }
    return null;
}
 
Example 3
Source File: CertificateUtils.java    From nifi-registry with Apache License 2.0 6 votes vote down vote up
/**
 * Extract extensions from CSR object
 */
public static Extensions getExtensionsFromCSR(JcaPKCS10CertificationRequest csr) {
    Attribute[] attributess = csr.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    for (Attribute attribute : attributess) {
        ASN1Set attValue = attribute.getAttrValues();
        if (attValue != null) {
            ASN1Encodable extension = attValue.getObjectAt(0);
            if (extension instanceof Extensions) {
                return (Extensions) extension;
            } else if (extension instanceof DERSequence) {
                return Extensions.getInstance(extension);
            }
        }
    }
    return null;
}
 
Example 4
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 5
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 6
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 7
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 8
Source File: CertificateUtils.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Extract extensions from CSR object
 */
public static Extensions getExtensionsFromCSR(JcaPKCS10CertificationRequest csr) {
    Attribute[] attributess = csr.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    for (Attribute attribute : attributess) {
        ASN1Set attValue = attribute.getAttrValues();
        if (attValue != null) {
            ASN1Encodable extension = attValue.getObjectAt(0);
            if (extension instanceof Extensions) {
                return (Extensions) extension;
            } else if (extension instanceof DERSequence) {
                return Extensions.getInstance(extension);
            }
        }
    }
    return null;
}
 
Example 9
Source File: CAdESSignature.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public Date getSigningTime() {
	final Attribute attr = getSignedAttribute(PKCSObjectIdentifiers.pkcs_9_at_signingTime);
	if (attr == null) {
		return null;
	}
	final ASN1Set attrValues = attr.getAttrValues();
	final ASN1Encodable attrValue = attrValues.getObjectAt(0);
	final Date signingDate = DSSASN1Utils.getDate(attrValue);
	if (signingDate != null) {
		/*
		 * RFC 3852 [4] states that "dates between January 1, 1950 and
		 * December 31, 2049 (inclusive) must be encoded as UTCTime. Any
		 * dates with year values before 1950 or after 2049 must be encoded
		 * as GeneralizedTime".
		 */
		if (signingDate.compareTo(JANUARY_1950) >= 0 && signingDate.before(JANUARY_2050)) {
			// must be ASN1UTCTime
			if (!(attrValue instanceof ASN1UTCTime)) {
				LOG.error(
						"RFC 3852 states that dates between January 1, 1950 and December 31, 2049 (inclusive) must be encoded as UTCTime. Any dates with year values before 1950 or after 2049 must be encoded as GeneralizedTime. Date found is {} encoded as {}",
						signingDate, attrValue.getClass());
				return null;
			}
		}
		return signingDate;
	}
	if (LOG.isErrorEnabled()) {
		LOG.error("Error when reading signing time. Unrecognized {}", attrValue.getClass());
	}
	return null;
}
 
Example 10
Source File: CAdESSignature.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public List<eu.europa.esig.dss.validation.CommitmentTypeIndication> getCommitmentTypeIndications() {
	final Attribute commitmentTypeIndicationAttribute = getSignedAttribute(PKCSObjectIdentifiers.id_aa_ets_commitmentType);
	if (commitmentTypeIndicationAttribute == null) {
		return null;
	}

	try {
		List<eu.europa.esig.dss.validation.CommitmentTypeIndication> commitmentTypeIndications = null;
		final ASN1Set attrValues = commitmentTypeIndicationAttribute.getAttrValues();
		final int size = attrValues.size();
		if (size > 0) {
			commitmentTypeIndications = new ArrayList<>();
			for (int ii = 0; ii < size; ii++) {
				if (attrValues.getObjectAt(ii) instanceof ASN1Sequence) {
					final ASN1Sequence sequence = (ASN1Sequence) attrValues.getObjectAt(ii);
					final CommitmentTypeIndication commitmentTypeIndication = CommitmentTypeIndication.getInstance(sequence);
					final ASN1ObjectIdentifier commitmentTypeId = commitmentTypeIndication.getCommitmentTypeId();
					commitmentTypeIndications.add(new eu.europa.esig.dss.validation.CommitmentTypeIndication(commitmentTypeId.getId()));
				} else {
					LOG.warn("Unsupported type for CommitmentType : {}", attrValues.getObjectAt(ii).getClass());
				}
			}
		}
		return commitmentTypeIndications;
	} catch (Exception e) {
		throw new DSSException("Error when dealing with CommitmentTypeIndication!", e);
	}
}
 
Example 11
Source File: CAdESSignature.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private SignerAttributeV2 getSignerAttributeV2() {
	final Attribute id_aa_ets_signerAttrV2 = getSignedAttribute(OID.id_aa_ets_signerAttrV2);
	if (id_aa_ets_signerAttrV2 != null) {
		final ASN1Set attrValues = id_aa_ets_signerAttrV2.getAttrValues();
		final ASN1Encodable attrValue = attrValues.getObjectAt(0);
		try {
			return SignerAttributeV2.getInstance(attrValue);
		} catch (Exception e) {
			LOG.warn("Unable to parse signerAttrV2 : {}", Utils.toBase64(DSSASN1Utils.getDEREncoded(attrValue)), e);
		}
	}
	return null;
}
 
Example 12
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 13
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 14
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 15
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;
}
 
Example 16
Source File: CAdESSignature.java    From dss with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public List<SignerRole> getCertifiedSignerRoles() {
	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();
		}
		List<SignerRole> roles = new ArrayList<>();
		for (final Object signerAttrValue : signerAttrValues) {
			if (signerAttrValue instanceof AttributeCertificate) {
				final AttributeCertificate attributeCertificate = (AttributeCertificate) signerAttrValue;
				final AttributeCertificateInfo acInfo = attributeCertificate.getAcinfo();
				final AttCertValidityPeriod attrCertValidityPeriod = acInfo.getAttrCertValidityPeriod();
				final ASN1Sequence attributes = acInfo.getAttributes();
				for (int ii = 0; ii < attributes.size(); ii++) {

					final ASN1Encodable objectAt = attributes.getObjectAt(ii);
					final org.bouncycastle.asn1.x509.Attribute attribute = org.bouncycastle.asn1.x509.Attribute.getInstance(objectAt);
					final ASN1Set attrValues1 = attribute.getAttrValues();
					ASN1Encodable firstItem = attrValues1.getObjectAt(0);
					if (firstItem instanceof ASN1Sequence) {
						ASN1Sequence sequence = (ASN1Sequence) firstItem;
						RoleSyntax roleSyntax = RoleSyntax.getInstance(sequence);
						SignerRole certifiedRole = new SignerRole(roleSyntax.getRoleNameAsString(), EndorsementType.CERTIFIED);
						certifiedRole.setNotBefore(DSSASN1Utils.toDate(attrCertValidityPeriod.getNotBeforeTime()));
						certifiedRole.setNotAfter(DSSASN1Utils.toDate(attrCertValidityPeriod.getNotAfterTime()));
						roles.add(certifiedRole);
					} else {
						LOG.warn("Unsupported type for RoleSyntax : {}", firstItem == null ? null : firstItem.getClass().getSimpleName());
					}
				}
			}
		}
		return roles;
	} catch (Exception e) {
		LOG.error("Error when dealing with certified signer roles : {}", signerAttrValues, e);
		return Collections.emptyList();
	}
}