org.bouncycastle.asn1.cms.SignedData Java Examples

The following examples show how to use org.bouncycastle.asn1.cms.SignedData. 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: CadesLevelBaselineLTATimestampExtractor.java    From dss with GNU Lesser General Public License v2.1 7 votes vote down vote up
/**
 * The field crlsHashIndex is a sequence of octet strings. Each one contains the
 * hash value of one instance of RevocationInfoChoice within crls field of the
 * root SignedData. A hash value for every instance of RevocationInfoChoice, as
 * present at the time when the corresponding archive time-stamp is requested,
 * shall be included in crlsHashIndex. No other hash values shall be included in
 * this field.
 *
 * @return
 * @throws eu.europa.esig.dss.model.DSSException
 */
@SuppressWarnings("unchecked")
private ASN1Sequence getCRLsHashIndex() {

	final ASN1EncodableVector crlsHashIndex = new ASN1EncodableVector();

	final SignedData signedData = SignedData.getInstance(cmsSignedData.toASN1Structure().getContent());
	final ASN1Set signedDataCRLs = signedData.getCRLs();
	if (signedDataCRLs != null) {
		final Enumeration<ASN1Encodable> crLs = signedDataCRLs.getObjects();
		if (crLs != null) {
			while (crLs.hasMoreElements()) {
				final ASN1Encodable asn1Encodable = crLs.nextElement();
				digestAndAddToList(crlsHashIndex, DSSASN1Utils.getDEREncoded(asn1Encodable));
			}
		}
	}

	return new DERSequence(crlsHashIndex);
}
 
Example #2
Source File: CAdESTimestampDataBuilder.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private byte[] getCertificateDataBytes(final SignedData signedData) throws IOException {
	byte[] certificatesBytes = null;
	
	final ASN1Set certificates = signedData.getCertificates();
	if (certificates != null) {
		/*
		 * In order to calculate correct message imprint it is important
		 * to use the correct encoding.
		 */
		if (certificates instanceof BERSet) {
			certificatesBytes = new BERTaggedObject(false, 0, new BERSequence(certificates.toArray())).getEncoded();
		} else {
			certificatesBytes = new DERTaggedObject(false, 0, new DERSequence(certificates.toArray())).getEncoded();
		}
		
		if (LOG.isTraceEnabled()) {
			LOG.trace("Certificates: {}", DSSUtils.toHex(certificatesBytes));
		}
	}
	if (LOG.isDebugEnabled()) {
		LOG.debug("Certificates are not present in the SignedData.");
	}
	return certificatesBytes;
}
 
Example #3
Source File: ScepResponder.java    From xipki with Apache License 2.0 6 votes vote down vote up
private SignedData getCrl(X509Ca ca, BigInteger serialNumber)
    throws FailInfoException, OperationException {
  if (!control.isSupportGetCrl()) {
    throw FailInfoException.BAD_REQUEST;
  }

  CertificateList crl = ca.getBcCurrentCrl();
  if (crl == null) {
    LOG.error("found no CRL");
    throw FailInfoException.BAD_REQUEST;
  }
  CMSSignedDataGenerator cmsSignedDataGen = new CMSSignedDataGenerator();
  cmsSignedDataGen.addCRL(new X509CRLHolder(crl));

  CMSSignedData signedData;
  try {
    signedData = cmsSignedDataGen.generate(new CMSAbsentContent());
  } catch (CMSException ex) {
    LogUtil.error(LOG, ex, "could not generate CMSSignedData");
    throw new OperationException(ErrorCode.SYSTEM_FAILURE, ex);
  }
  return SignedData.getInstance(signedData.toASN1Structure().getContent());
}
 
Example #4
Source File: ScepResponder.java    From xipki with Apache License 2.0 6 votes vote down vote up
private SignedData pollCert(X509Ca ca, X500Name subject, TransactionId tid)
    throws FailInfoException, OperationException {
  byte[] tidBytes = getTransactionIdBytes(tid.getId());
  List<X509Cert> certs = ca.getCert(subject, tidBytes);
  if (CollectionUtil.isEmpty(certs)) {
    certs = ca.getCert(subject, null);
  }

  if (CollectionUtil.isEmpty(certs)) {
    throw FailInfoException.BAD_CERTID;
  }

  if (certs.size() > 1) {
    LOG.warn("given certId (subject: {}) and transactionId {} match multiple certificates",
        X509Util.getRfc4519Name(subject), tid.getId());
    throw FailInfoException.BAD_CERTID;
  }

  return buildSignedData(certs.get(0));
}
 
Example #5
Source File: ScepResponder.java    From xipki with Apache License 2.0 6 votes vote down vote up
private SignedData getCert(X509Ca ca, BigInteger serialNumber)
    throws FailInfoException, OperationException {
  X509Cert cert;
  try {
    cert = ca.getCert(serialNumber);
  } catch (CertificateException ex) {
    final String message = "could not get certificate for CA '" + caIdent
        + "' and serialNumber=" + LogUtil.formatCsn(serialNumber) + ")";
    LogUtil.error(LOG, ex, message);
    throw new OperationException(ErrorCode.SYSTEM_FAILURE, ex);
  }
  if (cert == null) {
    throw FailInfoException.BAD_CERTID;
  }
  return buildSignedData(cert);
}
 
Example #6
Source File: AbstractRequirementChecks.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@BeforeEach
public void init() throws Exception {
	DSSDocument signedDocument = getSignedDocument();

	ASN1InputStream asn1sInput = new ASN1InputStream(signedDocument.openStream());
	ASN1Sequence asn1Seq = (ASN1Sequence) asn1sInput.readObject();
	assertEquals(2, asn1Seq.size());
	ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1Seq.getObjectAt(0));
	assertEquals(PKCSObjectIdentifiers.signedData, oid);

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

	ASN1Set signerInfosAsn1 = signedData.getSignerInfos();
	assertEquals(1, signerInfosAsn1.size());

	signerInfo = SignerInfo.getInstance(ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0)));

	Utils.closeQuietly(asn1sInput);
}
 
Example #7
Source File: CAdESTimestampDataBuilder.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private byte[] getCRLDataBytes(final SignedData signedData) throws IOException {
	byte[] crlBytes = null;
	
	final ASN1Set crLs = signedData.getCRLs();
	if (crLs != null) {
		
		if (signedData.getCRLs() instanceof BERSet) {
			crlBytes = new BERTaggedObject(false, 1, new BERSequence(crLs.toArray())).getEncoded();
		} else {
			crlBytes = new DERTaggedObject(false, 1, new DERSequence(crLs.toArray())).getEncoded();
		}
		if (LOG.isTraceEnabled()) {
			LOG.trace("CRLs: {}", DSSUtils.toHex(crlBytes));
		}
	}
	if (LOG.isDebugEnabled()) {
		LOG.debug("CRLs are not present in the SignedData.");
	}
	return crlBytes;
}
 
Example #8
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 #9
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 #10
Source File: Client.java    From xipki with Apache License 2.0 5 votes vote down vote up
public X509CRLHolder scepGetCrl(PrivateKey identityKey, X509Cert identityCert,
    X500Name issuer, BigInteger serialNumber) throws ScepClientException {
  Args.notNull(identityKey, "identityKey");
  Args.notNull(identityCert, "identityCert");
  Args.notNull(issuer, "issuer");
  Args.notNull(serialNumber, "serialNumber");

  initIfNotInited();

  PkiMessage pkiMessage = new PkiMessage(TransactionId.randomTransactionId(), MessageType.GetCRL);
  IssuerAndSerialNumber isn = new IssuerAndSerialNumber(issuer, serialNumber);
  pkiMessage.setMessageData(isn);
  ContentInfo request = encryptThenSign(pkiMessage, identityKey, identityCert);
  ScepHttpResponse httpResp = httpSend(Operation.PKIOperation, request);
  CMSSignedData cmsSignedData = parsePkiMessage(httpResp.getContentBytes());
  PkiMessage response = decode(cmsSignedData, identityKey, identityCert);
  if (response.getPkiStatus() != PkiStatus.SUCCESS) {
    throw new ScepClientException("server returned " + response.getPkiStatus());
  }

  ContentInfo messageData = ContentInfo.getInstance(response.getMessageData());

  try {
    return ScepUtil.getCrlFromPkiMessage(SignedData.getInstance(messageData.getContent()));
  } catch (CRLException ex) {
    throw new ScepClientException(ex.getMessage(), ex);
  }
}
 
Example #11
Source File: Client.java    From xipki with Apache License 2.0 5 votes vote down vote up
public List<X509Cert> scepGetCert(PrivateKey identityKey, X509Cert identityCert,
    X500Name issuer, BigInteger serialNumber) throws ScepClientException {
  Args.notNull(identityKey, "identityKey");
  Args.notNull(identityCert, "identityCert");
  Args.notNull(issuer, "issuer");
  Args.notNull(serialNumber, "serialNumber");

  initIfNotInited();

  PkiMessage request = new PkiMessage(TransactionId.randomTransactionId(), MessageType.GetCert);

  IssuerAndSerialNumber isn = new IssuerAndSerialNumber(issuer, serialNumber);
  request.setMessageData(isn);
  ContentInfo envRequest = encryptThenSign(request, identityKey, identityCert);
  ScepHttpResponse httpResp = httpSend(Operation.PKIOperation, envRequest);

  CMSSignedData cmsSignedData = parsePkiMessage(httpResp.getContentBytes());
  DecodedPkiMessage response = decode(cmsSignedData, identityKey, identityCert);
  if (response.getPkiStatus() != PkiStatus.SUCCESS) {
    throw new ScepClientException("server returned " + response.getPkiStatus());
  }

  ContentInfo messageData = ContentInfo.getInstance(response.getMessageData());
  try {
    return ScepUtil.getCertsFromSignedData(SignedData.getInstance(messageData.getContent()));
  } catch (CertificateException ex) {
    throw new ScepClientException(ex.getMessage(), ex);
  }
}
 
Example #12
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 #13
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 #14
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 #15
Source File: CadesLevelBaselineLTATimestampExtractor.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * The field crlsHashIndex is a sequence of octet strings. Each one contains the
 * hash value of one instance of RevocationInfoChoice within crls field of the
 * root SignedData. A hash value for every instance of RevocationInfoChoice, as
 * present at the time when the corresponding archive time-stamp is requested,
 * shall be included in crlsHashIndex. No other hash values shall be included in
 * this field.
 *
 * @return
 * @throws eu.europa.esig.dss.model.DSSException
 */
@SuppressWarnings("unchecked")
private ASN1Sequence getVerifiedCRLsHashIndex(final ASN1Sequence timestampHashIndex) {

	final ASN1Sequence crlHashes = DSSASN1Utils.getCRLHashIndex(timestampHashIndex);
	final List<DEROctetString> crlHashesList = DSSASN1Utils.getDEROctetStrings(crlHashes);

	final SignedData signedData = SignedData.getInstance(cmsSignedData.toASN1Structure().getContent());
	final ASN1Set signedDataCRLs = signedData.getCRLs();
	if (signedDataCRLs != null) {
		final Enumeration<ASN1Encodable> crLs = signedDataCRLs.getObjects();
		if (crLs != null) {
			while (crLs.hasMoreElements()) {
				final ASN1Encodable asn1Encodable = crLs.nextElement();
				handleRevocationEncoded(crlHashesList, DSSASN1Utils.getDEREncoded(asn1Encodable));
			}
		}
	}

	if (!crlHashesList.isEmpty()) {
		LOG.error("{} attribute(s) hash in CRL Hashes has not been found in document attributes: {}", crlHashesList.size(), crlHashesList);
		// return a empty DERSequence to screw up the hash
		return new DERSequence();
	}

	return crlHashes;
}
 
Example #16
Source File: ScepResponder.java    From xipki with Apache License 2.0 5 votes vote down vote up
private SignedData buildSignedData(X509Cert cert) throws OperationException {
  CMSSignedDataGenerator cmsSignedDataGen = new CMSSignedDataGenerator();
  try {
    cmsSignedDataGen.addCertificate(cert.toBcCert());
    if (control.isIncludeCaCert()) {
      refreshCa();
      cmsSignedDataGen.addCertificate(caCert.toBcCert());
    }
    CMSSignedData signedData = cmsSignedDataGen.generate(new CMSAbsentContent());
    return SignedData.getInstance(signedData.toASN1Structure().getContent());
  } catch (CMSException ex) {
    LogUtil.error(LOG, ex);
    throw new OperationException(ErrorCode.SYSTEM_FAILURE, ex);
  }
}
 
Example #17
Source File: CAdESTimestampDataBuilder.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private byte[] getContentInfoBytes(final SignedData signedData) {
	final ContentInfo content = signedData.getEncapContentInfo();
	byte[] contentInfoBytes;
	if (content.getContent() instanceof BEROctetString) {
		contentInfoBytes = DSSASN1Utils.getBEREncoded(content);
	} else {
		contentInfoBytes = DSSASN1Utils.getDEREncoded(content);
	}
	if (LOG.isTraceEnabled()) {
		LOG.trace("Content Info: {}", DSSUtils.toHex(contentInfoBytes));
	}
	return contentInfoBytes;
}
 
Example #18
Source File: CadesLevelBaselineLTATimestampExtractor.java    From dss with GNU Lesser General Public License v2.1 2 votes vote down vote up
/**
 * 1) The SignedData.encapContentInfo.eContentType.
 *
 * @param cmsSignedData
 * @return cmsSignedData.getSignedContentTypeOID() as DER encoded
 */
private byte[] getEncodedContentType(final CMSSignedData cmsSignedData) {
	final ContentInfo contentInfo = cmsSignedData.toASN1Structure();
	final SignedData signedData = SignedData.getInstance(contentInfo.getContent());
	return DSSASN1Utils.getDEREncoded(signedData.getEncapContentInfo().getContentType());
}