List of usage examples for org.bouncycastle.asn1.cms ContentInfo getInstance
public static ContentInfo getInstance(Object obj)
From source file:org.ejbca.core.protocol.scep.ScepRequestMessage.java
License:Open Source License
private void init() throws IOException { if (log.isTraceEnabled()) { log.trace(">init"); }/*w w w . jav a 2 s . c o m*/ try { CMSSignedData csd = new CMSSignedData(scepmsg); SignerInformationStore infoStore = csd.getSignerInfos(); @SuppressWarnings("unchecked") Collection<SignerInformation> signers = infoStore.getSigners(); Iterator<SignerInformation> iter = signers.iterator(); if (iter.hasNext()) { SignerInformation si = (SignerInformation) iter.next(); preferredDigestAlg = si.getDigestAlgOID(); log.debug("Set " + preferredDigestAlg + " as preferred digest algorithm for SCEP"); } } catch (CMSException e) { // ignore, use default digest algo log.error("CMSException trying to get preferred digest algorithm: ", e); } // Parse and verify the integrity of the PKIOperation message PKCS#7 /* If this would have been done using the newer CMS it would have made me so much happier... */ ASN1InputStream seqAsn1InputStream = new ASN1InputStream(new ByteArrayInputStream(scepmsg)); ASN1Sequence seq = null; try { seq = (ASN1Sequence) seqAsn1InputStream.readObject(); } finally { seqAsn1InputStream.close(); } ContentInfo ci = ContentInfo.getInstance(seq); String ctoid = ci.getContentType().getId(); if (ctoid.equals(CMSObjectIdentifiers.signedData.getId())) { // This is SignedData so it is a pkcsCertReqSigned, pkcsGetCertInitialSigned, pkcsGetCertSigned, pkcsGetCRLSigned // (could also be pkcsRepSigned or certOnly, but we don't receive them on the server side // Try to find out what kind of message this is sd = SignedData.getInstance((ASN1Sequence) ci.getContent()); // Get self signed cert to identify the senders public key ASN1Set certs = sd.getCertificates(); if (certs.size() > 0) { // There should be only one... ASN1Encodable dercert = certs.getObjectAt(0); if (dercert != null) { // Requester's self-signed certificate is requestKeyInfo ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); dOut.writeObject(dercert); if (bOut.size() > 0) { requestKeyInfo = bOut.toByteArray(); //Create Certificate used for debugging try { signercert = CertTools.getCertfromByteArray(requestKeyInfo); if (log.isDebugEnabled()) { log.debug("requestKeyInfo is SubjectDN: " + CertTools.getSubjectDN(signercert) + ", Serial=" + CertTools.getSerialNumberAsString(signercert) + "; IssuerDN: " + CertTools.getIssuerDN(signercert).toString()); } } catch (CertificateException e) { log.error("Error parsing requestKeyInfo : ", e); } } } } Enumeration<?> sis = sd.getSignerInfos().getObjects(); if (sis.hasMoreElements()) { SignerInfo si = SignerInfo.getInstance((ASN1Sequence) sis.nextElement()); Enumeration<?> attr = si.getAuthenticatedAttributes().getObjects(); while (attr.hasMoreElements()) { Attribute a = Attribute.getInstance((ASN1Sequence) attr.nextElement()); if (log.isDebugEnabled()) { log.debug("Found attribute: " + a.getAttrType().getId()); } if (a.getAttrType().getId().equals(id_senderNonce)) { Enumeration<?> values = a.getAttrValues().getObjects(); ASN1OctetString str = ASN1OctetString.getInstance(values.nextElement()); senderNonce = new String(Base64.encode(str.getOctets(), false)); if (log.isDebugEnabled()) { log.debug("senderNonce = " + senderNonce); } } if (a.getAttrType().getId().equals(id_transId)) { Enumeration<?> values = a.getAttrValues().getObjects(); DERPrintableString str = DERPrintableString.getInstance(values.nextElement()); transactionId = str.getString(); if (log.isDebugEnabled()) { log.debug("transactionId = " + transactionId); } } if (a.getAttrType().getId().equals(id_messageType)) { Enumeration<?> values = a.getAttrValues().getObjects(); DERPrintableString str = DERPrintableString.getInstance(values.nextElement()); messageType = Integer.parseInt(str.getString()); if (log.isDebugEnabled()) { log.debug("messagetype = " + messageType); } } } } // If this is a PKCSReq if ((messageType == ScepRequestMessage.SCEP_TYPE_PKCSREQ) || (messageType == ScepRequestMessage.SCEP_TYPE_GETCRL) || (messageType == ScepRequestMessage.SCEP_TYPE_GETCERTINITIAL)) { // Extract the contents, which is an encrypted PKCS10 if messageType == 19 // , and an encrypted issuer and subject if messageType == 20 (not extracted) // and an encrypted IssuerAndSerialNumber if messageType == 22 ci = sd.getEncapContentInfo(); ctoid = ci.getContentType().getId(); if (ctoid.equals(CMSObjectIdentifiers.data.getId())) { ASN1OctetString content = (ASN1OctetString) ci.getContent(); if (log.isDebugEnabled()) { log.debug("envelopedData is " + content.getOctets().length + " bytes."); } ASN1InputStream seq1Asn1InputStream = new ASN1InputStream( new ByteArrayInputStream(content.getOctets())); ASN1Sequence seq1 = null; try { seq1 = (ASN1Sequence) seq1Asn1InputStream.readObject(); } finally { seq1Asn1InputStream.close(); } envEncData = ContentInfo.getInstance(seq1); ctoid = envEncData.getContentType().getId(); if (ctoid.equals(CMSObjectIdentifiers.envelopedData.getId())) { envData = EnvelopedData.getInstance((ASN1Sequence) envEncData.getContent()); ASN1Set recipientInfos = envData.getRecipientInfos(); Enumeration<?> e = recipientInfos.getObjects(); while (e.hasMoreElements()) { RecipientInfo ri = RecipientInfo.getInstance(e.nextElement()); KeyTransRecipientInfo recipientInfo = KeyTransRecipientInfo.getInstance(ri.getInfo()); RecipientIdentifier rid = recipientInfo.getRecipientIdentifier(); IssuerAndSerialNumber iasn = IssuerAndSerialNumber.getInstance(rid.getId()); issuerDN = iasn.getName().toString(); serialNo = iasn.getSerialNumber().getValue(); if (log.isDebugEnabled()) { log.debug("IssuerDN: " + issuerDN); log.debug("SerialNumber: " + iasn.getSerialNumber().getValue().toString(16)); } } } else { errorText = "EncapsulatedContentInfo does not contain PKCS7 envelopedData: "; log.error(errorText + ctoid); error = 2; } } else { errorText = "EncapsulatedContentInfo is not of type 'data': "; log.error(errorText + ctoid); error = 3; } } else { errorText = "This is not a certification request!"; log.error(errorText); error = 4; } } else { errorText = "PKCSReq does not contain 'signedData': "; log.error(errorText + ctoid); error = 1; } log.trace("<init"); }
From source file:org.icepdf.core.pobjects.acroform.signature.AbstractPkcsValidator.java
License:Apache License
/** * SignedData ::= SEQUENCE {//from w ww .jav a 2 s. c o m * 0, version CMSVersion, * 1, digestAlgorithms DigestAlgorithmIdentifiers, * 2, encapContentInfo EncapsulatedContentInfo, * 3, certificateChain [0] IMPLICIT CertificateSet OPTIONAL, * 4, crls [1] IMPLICIT RevocationInfoChoices OPTIONAL, * 5, signerInfos SignerInfos } * <p/> * DigestAlgorithmIdentifiers ::= SET OF DigestAlgorithmIdentifier * SignerInfos ::= SET OF SignerInfo */ protected void parseSignerData(ASN1Sequence signedData, byte[] cmsData) throws SignatureIntegrityException { // digest algorithms ID, not currently using them but useful for debug. if (logger.isLoggable(Level.FINER)) { // should always be 1. int cmsVersion = ((ASN1Integer) signedData.getObjectAt(0)).getValue().intValue(); logger.finest("CMS version: " + cmsVersion); Enumeration<ASN1Sequence> enumeration = ((ASN1Set) signedData.getObjectAt(1)).getObjects(); while (enumeration.hasMoreElements()) { String objectId = ((ASN1ObjectIdentifier) enumeration.nextElement().getObjectAt(0)).getId(); try { String digestAlgorithmName = AlgorithmIdentifier.getDigestAlgorithmName(objectId); MessageDigest tmp = AlgorithmIdentifier.getDigestInstance(objectId, null); logger.finest("DigestAlgorithmIdentifiers: " + digestAlgorithmName + " " + objectId); logger.finest(tmp.toString()); } catch (Throwable ex) { logger.log(Level.WARNING, "Error finding iod: " + objectId, ex); } } } /** * EncapsulatedContentInfo ::= SEQUENCE { * eContentType ContentType, * eContent [0] EXPLICIT OCTET STRING OPTIONAL } * * ContentType ::= OBJECT IDENTIFIER */ encapsulatedContentInfoData = null; ASN1Sequence encapsulatedContentInfo = (ASN1Sequence) signedData.getObjectAt(2); // grab just the first definitions, as we are looking for encapuslated data for PKCS7.sha1. if (encapsulatedContentInfo.size() >= 2) { // should still be iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs7(7) 1 ... ASN1ObjectIdentifier eObjectIdentifier = (ASN1ObjectIdentifier) encapsulatedContentInfo.getObjectAt(0); String eObjectIdentifierId = eObjectIdentifier.getId(); if (logger.isLoggable(Level.FINER)) { logger.finest("EncapsulatedContentInfo: " + eObjectIdentifierId + " " + Pkcs7Validator.getObjectIdName(eObjectIdentifierId)); } // should be octets encode as pkcs#7 ASN1OctetString eContent = (ASN1OctetString) ((ASN1TaggedObject) encapsulatedContentInfo.getObjectAt(1)) .getObject(); // shows up in pkcs7.sha1 only encapsulatedContentInfoData = eContent.getOctets(); if (logger.isLoggable(Level.FINER)) { logger.finest("EncapsulatedContentInfo Data " + eContent.toString()); } } else if (encapsulatedContentInfo.size() == 1) { if (logger.isLoggable(Level.FINER)) { ASN1ObjectIdentifier eObjectIdentifier = (ASN1ObjectIdentifier) encapsulatedContentInfo .getObjectAt(0); String eObjectIdentifierId = eObjectIdentifier.getId(); logger.finest("EncapsulatedContentInfo size is 1: " + eObjectIdentifierId + " " + Pkcs7Validator.getObjectIdName(eObjectIdentifierId)); } } // grab the signer info. ASN1Sequence signerInfo = parseCertificateData(cmsData, signedData); // DigestAlgorithmIdentifier ::= AlgorithmIdentifier digestAlgorithmIdentifier = ((ASN1ObjectIdentifier) ((ASN1Sequence) signerInfo.getObjectAt(2)) .getObjectAt(0)).getId(); // signedAttrs [0] IMPLICIT SignedAttributes OPTIONAL, // signedAttrs is optional so we look for the occurrence // // SignedAttributes ::= SET SIZE (1..MAX) OF Attribute // // Attribute ::= SEQUENCE { // attrType OBJECT IDENTIFIER, // attrValues SET OF AttributeValue } // // AttributeValue ::= ANY // SignatureValue ::= OCTET STRING int nextEntry = 3; messageDigest = null; ASN1TaggedObject signedAttributes; signedAttributesSequence = null; if (signerInfo.getObjectAt(nextEntry) instanceof ASN1TaggedObject) { signedAttributes = (ASN1TaggedObject) signerInfo.getObjectAt(nextEntry); signedAttributesSequence = ASN1Set.getInstance(signedAttributes, false); for (int i = 0, max = signedAttributesSequence.size(); i < max; ++i) { // attribute type/value pair. ASN1Sequence attributePair = (ASN1Sequence) signedAttributesSequence.getObjectAt(i); // mainly just looking for the message digest. if (((ASN1ObjectIdentifier) attributePair.getObjectAt(0)).getId() .equals(PKCSObjectIdentifiers.pkcs_9_at_messageDigest.getId())) { ASN1Set set = (ASN1Set) attributePair.getObjectAt(1); messageDigest = ((ASN1OctetString) set.getObjectAt(0)).getOctets(); } // try and pull out the signing time. // currently not using this time. // if (((ASN1ObjectIdentifier) attributePair.getObjectAt(0)).getId().equals( // PKCSObjectIdentifiers.pkcs_9_at_signingTime.getId())) { // ASN1Set set = (ASN1Set) attributePair.getObjectAt(1); // ASN1UTCTime signerTime = ((ASN1UTCTime) set.getObjectAt(0)); // try { // // see if the signer time matches the certificate validity times. // System.out.println(" SignatureSigner Time " + signerTime.getDate()); // } catch (ParseException e) { // e.printStackTrace(); // } // } // more attributes to come. } if (messageDigest == null) { throw new SignatureIntegrityException("Message Digest can nut be null"); } ++nextEntry; } // signatureAlgorithm SignatureAlgorithmIdentifier, signatureAlgorithmIdentifier = ((ASN1ObjectIdentifier) ((ASN1Sequence) signerInfo.getObjectAt(nextEntry)) .getObjectAt(0)).getId(); nextEntry++; // signature SignatureValue signatureValue = ((ASN1OctetString) signerInfo.getObjectAt(nextEntry)).getOctets(); nextEntry++; // unsignedAttrs [1] IMPLICIT UnsignedAttributes OPTIONAL // once again optional so we check to see if the entry is available. if (nextEntry < signerInfo.size() && signerInfo.getObjectAt(nextEntry) instanceof ASN1TaggedObject) { ASN1TaggedObject unsignedAttributes = (ASN1TaggedObject) signerInfo.getObjectAt(nextEntry); ASN1Set unsignedAttributeSequence = ASN1Set.getInstance(unsignedAttributes, false); AttributeTable attributeTable = new AttributeTable(unsignedAttributeSequence); Attribute timeStamp = attributeTable.get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken); if (timeStamp != null && timeStamp.getAttrValues().size() > 0) { ASN1Set attributeValues = timeStamp.getAttrValues(); ASN1Sequence tokenSequence = ASN1Sequence.getInstance(attributeValues.getObjectAt(0)); ContentInfo contentInfo = ContentInfo.getInstance(tokenSequence); // if we can parse it we call it good, so cert has a embedded time but we don't do any validation on it try { new TimeStampToken(contentInfo); isEmbeddedTimeStamp = true; } catch (Throwable e1) { throw new SignatureIntegrityException("Valid TimeStamp could now be created"); } } } }
From source file:org.jnotary.dvcs.CertEtcToken.java
License:Open Source License
private CertEtcToken(Object obj) { if (obj instanceof X509Extension) { extension = null; //TODO: Das muss verstanden werden } else {/*from www. j ava2 s.c o m*/ ASN1TaggedObject tagObj = (ASN1TaggedObject) obj; switch (tagObj.getTagNo()) { case 0: certificate = Certificate.getInstance(tagObj.getObject()); break; case 1: esscertid = ESSCertID.getInstance(tagObj.getObject()); break; case 2: pkistatus = PKIStatusInfo.getInstance(tagObj.getObject()); break; case 3: assertion = ContentInfo.getInstance(tagObj.getObject()); break; case 4: crl = CertificateList.getInstance(tagObj.getObject()); break; case 5: ocspcertstatus = CertStatus.getInstance(tagObj.getObject()); break; case 6: oscpcertid = CertID.getInstance(tagObj.getObject()); break; case 7: oscpresponse = OCSPResponse.getInstance(tagObj.getObject()); break; case 8: capabilities = SMIMECapabilities.getInstance(tagObj.getObject()); break; } } }
From source file:org.jnotary.dvcs.DVCSTime.java
License:Open Source License
private DVCSTime(Object obj) { if (obj instanceof ASN1GeneralizedTime) genTime = DERGeneralizedTime.getInstance(obj); else/*w w w. ja v a2s . co m*/ timeStampToken = ContentInfo.getInstance(obj); }
From source file:org.jruby.ext.openssl.x509store.PEMInputOutput.java
License:LGPL
/** * Reads in a PKCS7 object. This returns a ContentInfo object suitable for use with the CMS * API./*from ww w .ja va 2s . c om*/ * * @return the X509Certificate * @throws IOException if an I/O error occured */ private static CMSSignedData readPKCS7(BufferedReader in, char[] p, String endMarker) throws IOException { String line; StringBuilder buf = new StringBuilder(); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); while ((line = in.readLine()) != null) { if (line.indexOf(endMarker) != -1) { break; } line = line.trim(); buf.append(line.trim()); Base64.decode(buf.substring(0, (buf.length() / 4) * 4), bOut); buf.delete(0, (buf.length() / 4) * 4); } if (buf.length() != 0) { throw new RuntimeException("base64 data appears to be truncated"); } if (line == null) { throw new IOException(endMarker + " not found"); } try { ASN1InputStream aIn = new ASN1InputStream(bOut.toByteArray()); return new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); } catch (Exception e) { throw new IOException("problem parsing PKCS7 object: " + e.toString()); } }
From source file:org.jscep.content.NextCaCertificateContentHandler.java
License:Open Source License
/** * {@inheritDoc}//from w w w.ja v a 2 s. c o m */ public List<X509Certificate> getContent(InputStream in, String mimeType) throws IOException { LOGGER.entering(getClass().getName(), "getContent", new Object[] { in, mimeType }); if (mimeType.equals("application/x-x509-next-ca-cert")) { // http://tools.ietf.org/html/draft-nourse-scep-20#section-4.6.1 // The response consists of a SignedData PKCS#7 [RFC2315], // signed by the current CA (or RA) signing key. final List<X509Certificate> certs = new ArrayList<X509Certificate>(); Collection<? extends Certificate> collection; try { CMSSignedData cmsMessageData = new CMSSignedData(getBytes(in)); ContentInfo cmsContentInfo = ContentInfo .getInstance(ASN1Object.fromByteArray(cmsMessageData.getEncoded())); // TODO: This must be signed by the current CA. final SignedData sd = SignedData.getInstance(cmsContentInfo.getContent()); if (SignedDataUtil.isSignedBy(sd, issuer) == false) { IOException ioe = new IOException("Invalid Signer"); LOGGER.throwing(getClass().getName(), "getContent", ioe); throw ioe; } // The content of the SignedData PKCS#7 [RFC2315] is a degenerate // certificates-only Signed-data (Section 3.3) message containing the // new CA certificate and any new RA certificates, as defined in // Section 5.2.1.1.2, to be used when the current CA certificate // expires. CertStore store = SignedDataUtil.extractCertStore(sd); collection = store.getCertificates(new X509CertSelector()); } catch (GeneralSecurityException e) { final IOException ioe = new IOException(e); LOGGER.throwing(getClass().getName(), "getContent", ioe); throw ioe; } catch (CMSException e) { final IOException ioe = new IOException(e); LOGGER.throwing(getClass().getName(), "getContent", ioe); throw ioe; } for (Certificate cert : collection) { certs.add((X509Certificate) cert); } LOGGER.exiting(getClass().getName(), "getContent", certs); return certs; } else { IOException ioe = new IOException("Invalid Content Type"); LOGGER.throwing(getClass().getName(), "getContent", ioe); throw ioe; } }
From source file:org.jscep.pkcs7.SignedDataParser.java
License:Open Source License
/** * Parses the provided ASN1 object and extracts a degenerate SignedData * instance./* ww w . ja v a2 s . c o m*/ * * @param signedData the ASN1 object to parse. * @return a new degenerate SignedData instance. * @throws IOException if any I/O error occurs. */ public SignedData parse(ASN1Encodable signedData) throws IOException { LOGGER.entering(getClass().getName(), "parse", signedData); try { ContentInfo ci = ContentInfo.getInstance(signedData); ASN1Sequence seq = (ASN1Sequence) ci.getContent(); final SignedData sd = new SignedData(seq); LOGGER.exiting(getClass().getName(), "parse", sd); return sd; } catch (Exception e) { LOGGER.throwing(getClass().getName(), "parse", e); throw new IOException(e); } }
From source file:org.votingsystem.signature.util.CMSUtils.java
License:Open Source License
private static ContentInfo readContentInfo(ASN1InputStream in) throws CMSException { try {//from www . j av a 2 s. c om return ContentInfo.getInstance(in.readObject()); } catch (IOException e) { throw new CMSException("IOException reading content.", e); } catch (ClassCastException e) { throw new CMSException("Malformed content.", e); } catch (IllegalArgumentException e) { throw new CMSException("Malformed content.", e); } }
From source file:org.votingsystem.signature.util.TimeStampResponseGenerator.java
License:Open Source License
/** @deprecated */ public TimeStampResponse generate(TimeStampRequest request, BigInteger serialNumber, Date genTime, String provider) throws NoSuchAlgorithmException, NoSuchProviderException, TSPException { TimeStampResp resp;/*from w w w. ja va 2s . c om*/ PKIStatusInfo pkiStatusInfo; try { if (genTime == null) { throw new TSPValidationException("The time source is not available.", 512); } request.validate(this.acceptedAlgorithms, this.acceptedPolicies, this.acceptedExtensions, provider); this.status = 0; this.addStatusString("Operation OK"); PKIStatusInfo e = this.getPKIStatusInfo(); pkiStatusInfo = null; ContentInfo pkiStatusInfo1; try { ByteArrayInputStream ioEx = new ByteArrayInputStream(this.tokenGenerator .generate(request, serialNumber, genTime, provider).toCMSSignedData().getEncoded()); ASN1InputStream aIn = new ASN1InputStream(ioEx); pkiStatusInfo1 = ContentInfo.getInstance(aIn.readObject()); } catch (IOException var11) { throw new TSPException("Timestamp token received cannot be converted to ContentInfo", var11); } resp = new TimeStampResp(e, pkiStatusInfo1); } catch (TSPValidationException var12) { this.status = 2; this.setFailInfoField(var12.getFailureCode()); this.addStatusString(var12.getMessage()); pkiStatusInfo = this.getPKIStatusInfo(); resp = new TimeStampResp(pkiStatusInfo, (ContentInfo) null); } try { return new TimeStampResponse(resp); } catch (IOException var10) { throw new TSPException("created badly formatted response!"); } }
From source file:org.votingsystem.signature.util.TimeStampResponseGenerator.java
License:Open Source License
public TimeStampResponse generate(TimeStampRequest request, BigInteger serialNumber, Date genTime) throws TSPException { this.statusStrings = new ASN1EncodableVector(); TimeStampResp resp;/*from ww w . j a v a 2 s . c om*/ PKIStatusInfo pkiStatusInfo; try { if (genTime == null) { throw new TSPValidationException("The time source is not available.", 512); } request.validate(this.acceptedAlgorithms, this.acceptedPolicies, this.acceptedExtensions); this.status = 0; this.addStatusString("Operation Okay"); PKIStatusInfo e = this.getPKIStatusInfo(); pkiStatusInfo = null; ContentInfo pkiStatusInfo1; try { ByteArrayInputStream ioEx = new ByteArrayInputStream(this.tokenGenerator .generate(request, serialNumber, genTime).toCMSSignedData().getEncoded()); ASN1InputStream aIn = new ASN1InputStream(ioEx); pkiStatusInfo1 = ContentInfo.getInstance(aIn.readObject()); } catch (IOException var10) { throw new TSPException("Timestamp token received cannot be converted to ContentInfo", var10); } resp = new TimeStampResp(e, pkiStatusInfo1); } catch (TSPValidationException var11) { this.status = 2; this.setFailInfoField(var11.getFailureCode()); this.addStatusString(var11.getMessage()); pkiStatusInfo = this.getPKIStatusInfo(); resp = new TimeStampResp(pkiStatusInfo, (ContentInfo) null); } try { return new TimeStampResponse(resp); } catch (IOException var9) { throw new TSPException("created badly formatted response!"); } }