List of usage examples for org.bouncycastle.asn1.cms CMSObjectIdentifiers data
ASN1ObjectIdentifier data
To view the source code for org.bouncycastle.asn1.cms CMSObjectIdentifiers data.
Click Source Link
From source file:CMSProcessableInputStream.java
License:Apache License
CMSProcessableInputStream(InputStream is) {
this(new ASN1ObjectIdentifier(CMSObjectIdentifiers.data.getId()), is);
}
From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java
License:Open Source License
@SuppressWarnings("unchecked") static protected SignedData includeCrls(byte[] assinatura, Collection crls) throws IOException, Exception, SecurityException, CRLException, NoSuchProviderException, NoSuchAlgorithmException { org.bouncycastle.asn1.pkcs.SignedData pkcs7 = pkcs7SignedData(assinatura); ContentInfo content = new ContentInfo(CMSObjectIdentifiers.data, null); SignedData signedCms = new SignedData(pkcs7.getDigestAlgorithms(), content, pkcs7.getCertificates(), pkcs7.getCRLs(), pkcs7.getSignerInfos()); ASN1EncodableVector vec = new ASN1EncodableVector(); for (X509CRLObject crl : (Collection<X509CRLObject>) crls) vec.add(ASN1Primitive.fromByteArray(crl.getEncoded())); DERSet set = new DERSet(vec); // for (X509CRLObject crl : (Collection<X509CRLObject>) crls) // set.addObject(ASN1Object.fromByteArray(crl.getEncoded())); SignedData signedCmsWithCrls = new SignedData(signedCms.getDigestAlgorithms(), signedCms.getEncapContentInfo(), signedCms.getCertificates(), set, signedCms.getSignerInfos()); signedCmsWithCrls.getCertificates(); signedCmsWithCrls.getCRLs();/* w w w .jav a2 s .c om*/ return signedCmsWithCrls; }
From source file:es.gob.afirma.envelopers.cms.CMSCompressedData.java
License:Open Source License
/** Obtiene un tipo CompressedData. * @param data/*w w w .java 2 s .c om*/ * Datos a comprimir * @return Tipo CompressedData. * @throws IOException En caso de error en la lectura o tratamiento de datos */ static byte[] genCompressedData(final byte[] data) throws IOException { // Algoritmo de compresion final AlgorithmIdentifier comAlgId = new AlgorithmIdentifier(new ASN1ObjectIdentifier(ZLIB)); // Se comprimen los datos final byte[] compressed = BinaryUtils.compress(data); final ASN1OctetString comOcts = new BEROctetString(compressed); // Contenido comprimido final ContentInfo comContent = new ContentInfo(CMSObjectIdentifiers.data, comOcts); return new ContentInfo(CMSObjectIdentifiers.compressedData, new CompressedData(comAlgId, comContent)) .getEncoded(ASN1Encoding.DER); }
From source file:it.trento.comune.j4sign.cms.utils.CMSBuilder.java
License:Open Source License
private Date parseSigningTime(byte[] bytes, PrintWriter pw) { Date parsedSigningTime = null; try {//from ww w .ja v a 2 s.c o m ASN1InputStream aIn = new ASN1InputStream(bytes); ASN1Set signedAttributes = (ASN1Set) aIn.readObject(); AttributeTable attr = new AttributeTable(signedAttributes); Iterator iter = attr.toHashtable().values().iterator(); pw.println("Listing authenticated attributes:"); int count = 1; while (iter.hasNext()) { Attribute a = (Attribute) iter.next(); pw.println("Attribute " + count + ":"); if (a.getAttrType().getId().equals(CMSAttributes.signingTime.getId())) { Time time = Time.getInstance(a.getAttrValues().getObjectAt(0)); pw.println("Authenticated time (SERVER local time): " + time.getDate()); parsedSigningTime = time.getDate(); } if (a.getAttrType().getId().equals(CMSAttributes.contentType.getId())) { if (CMSObjectIdentifiers.data.getId() .equals(DERObjectIdentifier.getInstance(a.getAttrValues().getObjectAt(0)).getId())) pw.println("Content Type: PKCS7_DATA"); } if (a.getAttrType().getId().equals(CMSAttributes.messageDigest.getId())) { byte[] md = DEROctetString.getInstance(a.getAttrValues().getObjectAt(0)).getOctets(); pw.println("Message Digest (hash of data content): " + formatAsString(md, " ", 16)); } pw.println("\nAttribute dump follows:"); pw.println(ASN1Dump.dumpAsString(a) + "\n"); count++; } } catch (Exception e) { pw.println(e); return null; } pw.flush(); return parsedSigningTime; }
From source file:it.trento.comune.j4sign.cms.utils.CMSVerifier.java
License:Open Source License
private void parseAuthenticatedAttributes(SignerInformation signer) { AttributeTable attr = signer.getSignedAttributes(); Iterator<Attribute> iter = attr.toHashtable().values().iterator(); if (debug)//from ww w . j a v a2s. c o m System.out.println("Listing authenticated attributes:"); int count = 1; while (iter.hasNext()) { Attribute a = iter.next(); if (debug) System.out.println("Attribute " + count + ":"); if (a.getAttrType().getId().equals(CMSAttributes.signingTime.getId())) { Time time = Time.getInstance(a.getAttrValues().getObjectAt(0)); if (debug) System.out.println("Authenticated time: " + time.getDate()); this.signingTime = time.getDate(); } if (a.getAttrType().getId().equals(CMSAttributes.contentType.getId())) { if (CMSObjectIdentifiers.data.getId() .equals(DERObjectIdentifier.getInstance(a.getAttrValues().getObjectAt(0)).getId())) if (debug) System.out.println("Content Type: PKCS7_DATA"); } if (a.getAttrType().getId().equals(CMSAttributes.messageDigest.getId())) { byte[] md = DEROctetString.getInstance(a.getAttrValues().getObjectAt(0)).getOctets(); if (debug) System.out.println( "Message Digest (hash of data content):\n" + CMSBuilder.formatAsString(md, " ", 16)); } if (debug) System.out.println("\nAttribute dump follows:"); if (debug) System.out.println(ASN1Dump.dumpAsString(a) + "\n"); count++; } }
From source file:it.trento.comune.j4sign.examples.CMSServlet.java
License:Open Source License
/** * A text message resulting from a dump of provided authenticated attributes * data. Shows, among other things, the embedded timestamp attribute. * /*from w w w.j av a 2s . c om*/ * @param bytes * the ASN.1 DER set of authenticated attributes. * @return the attributes textual dump. */ private String getAuthenticatedAttributesPrintout(byte[] bytes) { StringWriter printout = new StringWriter(); PrintWriter pw = new PrintWriter(printout); try { ASN1StreamParser a1p = new ASN1StreamParser(bytes); System.out.println("ASN1 parser built: " + a1p); DERSetParser signedAttributesParser = (DERSetParser) a1p.readObject(); System.out.println("DERSetParser object read: " + signedAttributesParser); ASN1Set set = ASN1Set.getInstance(signedAttributesParser.getDERObject()); AttributeTable attr = new AttributeTable(set); System.out.println("Attribute table created: " + attr); Iterator iter = attr.toHashtable().values().iterator(); pw.println("Listing authenticated attributes:"); int count = 1; while (iter.hasNext()) { Attribute a = (Attribute) iter.next(); pw.println("Attribute " + count + ":"); if (a.getAttrType().getId().equals(CMSAttributes.signingTime.getId())) { Time time = Time.getInstance(a.getAttrValues().getObjectAt(0)); pw.println("Authenticated time (SERVER local time): " + time.getDate()); } if (a.getAttrType().getId().equals(CMSAttributes.contentType.getId())) { if (CMSObjectIdentifiers.data.getId() .equals(DERObjectIdentifier.getInstance(a.getAttrValues().getObjectAt(0)).getId())) pw.println("Content Type: PKCS7_DATA"); } if (a.getAttrType().getId().equals(CMSAttributes.messageDigest.getId())) { byte[] md = DEROctetString.getInstance(a.getAttrValues().getObjectAt(0)).getOctets(); pw.println("Message Digest (SHA-256 hash of data content): " + formatAsString(md, " ")); } if (a.getAttrType().getId().equals(PKCSObjectIdentifiers.id_aa_signingCertificateV2.getId())) { pw.println("Signing Certificate V2"); } pw.println("\nAttribute dump follows:"); pw.println(ASN1Dump.dumpAsString(a) + "\n"); count++; } } catch (Exception e) { System.out.println(e); pw.println(e); return null; } pw.flush(); return printout.toString(); }
From source file:it.trento.comune.j4sign.verification.VerifyResult.java
License:Open Source License
/** * Main signature verification and signature attributes correctness<br> * <br>/*w ww .j a v a 2 s .c om*/ * Verifica principale della firma e di correttezza degli attributi. * * @return boolean */ public boolean checkIntegrity() { this.integrityChecked = this.messageDigestPresent = this.contentTypeDataPresent = false; if (signer == null) { log.info("No signers"); return integrityChecked; } log.info("\nSigner DN: " + cert.getSubjectDN() + "\nSigner SID: " + signer.getSID().toString() + "\n"); // ===== List authenticated attributes ========= AttributeTable attrs = signer.getSignedAttributes(); if (attrs == null) { log.info("No authenticated attributes!"); return false; } Iterator<Attribute> iter = attrs.toHashtable().values().iterator(); log.info("Listing authenticated attributes:"); int count = 1; while (iter.hasNext()) { Attribute a = iter.next(); log.info("Attribute " + count + ")"); if (a.getAttrType().getId().equals(CMSAttributes.contentType.getId())) { if (CMSObjectIdentifiers.data.getId() .equals(DERObjectIdentifier.getInstance(a.getAttrValues().getObjectAt(0)).getId())) this.contentTypeDataPresent = true; log.info("Content Type: PKCS7_DATA"); } if (a.getAttrType().getId().equals(CMSAttributes.messageDigest.getId())) { byte[] md = DEROctetString.getInstance(a.getAttrValues().getObjectAt(0)).getOctets(); this.messageDigestPresent = true; log.info("Message Digest:\n" + CertUtils.formatAsHexString(md)); } if (a.getAttrType().getId().equals(PKCSObjectIdentifiers.id_aa_signingCertificateV2.getId())) log.info("Reference to signing certificate (CAdES): signingCertificateV2"); if (a.getAttrType().getId().equals(CMSAttributes.signingTime.getId())) { Time time = Time.getInstance(a.getAttrValues().getObjectAt(0)); log.info("Signing time: " + time.getDate()); this.signingTime = time.getDate(); } log.info("\nAttribute dump follows:"); log.info(ASN1Dump.dumpAsString(a) + "\n"); count++; } signingAlgorithmName = new DefaultCMSSignatureAlgorithmNameGenerator().getSignatureName( AlgorithmIdentifier.getInstance(signer.getDigestAlgOID()), AlgorithmIdentifier.getInstance(signer.getEncryptionAlgOID())); log.info("\nSigning algorithm is : " + signingAlgorithmName + "\n"); try { // BC API version 2 /* * Note: we should test for EncryptionAlg = RSA before doing * this!!!! integrityChecked = signer .verify(new * BcRSASignerInfoVerifierBuilder( new * DefaultDigestAlgorithmIdentifierFinder(), new * BcDigestCalculatorProvider()) .build(new * X509CertificateHolder(cert.getEncoded()))); */ integrityChecked = signer.verify( new JcaSimpleSignerInfoVerifierBuilder().build(new X509CertificateHolder(cert.getEncoded()))); // Now deprecated // integrityChecked = signer.verify(cert, "BC"); } catch (CMSException ex) { System.out.println(ex.getMessage()); } catch (CertificateNotYetValidException ex) { System.out.println(ex.getMessage()); } catch (CertificateExpiredException ex) { System.out.println(ex.getMessage()); } catch (CertificateException e) { System.out.println(e.getMessage()); } catch (OperatorCreationException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } return integrityChecked; }
From source file:mitm.common.security.cms.CMSContentTypeClassifier.java
License:Open Source License
/** * Returns the CMS content type of the provided sequence. * /*from w w w. ja v a 2 s .co m*/ * See RFC3852 for content types * * @param sequenceParser * @return */ public static CMSContentType getContentType(ASN1SequenceParser sequenceParser) { CMSContentType contentType = CMSContentType.UNKNOWN; try { ContentInfoParser contentInfoParser = new ContentInfoParser(sequenceParser); DERObjectIdentifier derContentType = contentInfoParser.getContentType(); if (CMSObjectIdentifiers.data.equals(derContentType)) { contentType = CMSContentType.DATA; } else if (CMSObjectIdentifiers.signedData.equals(derContentType)) { contentType = CMSContentType.SIGNEDDATA; } else if (CMSObjectIdentifiers.envelopedData.equals(derContentType)) { contentType = CMSContentType.ENVELOPEDDATA; } else if (CMSObjectIdentifiers.signedAndEnvelopedData.equals(derContentType)) { contentType = CMSContentType.SIGNEDANDENVELOPEDDATA; } else if (CMSObjectIdentifiers.digestedData.equals(derContentType)) { contentType = CMSContentType.DIGESTEDDATA; } else if (CMSObjectIdentifiers.encryptedData.equals(derContentType)) { contentType = CMSContentType.ENCRYPTEDDATA; } else if (CMSObjectIdentifiers.compressedData.equals(derContentType)) { contentType = CMSContentType.COMPRESSEDDATA; } } catch (IOException e) { logger.error("IOException retrieving CMS content type", e); } return contentType; }
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 .ja va 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.votingsystem.signature.dnie.DNIePDFContentSigner.java
License:Open Source License
public CMSSignedData getCMSSignedData(String eContentType, CMSProcessable content, boolean encapsulate, Provider sigProvider, boolean addDefaultAttributes, List signerInfs) throws Exception { // TODO if (signerInfs.isEmpty()){ // /* RFC 3852 5.2 // * "In the degenerate case where there are no signers, the // * EncapsulatedContentInfo value being "signed" is irrelevant. In this // * case, the content type within the EncapsulatedContentInfo value being // * "signed" MUST be id-data (as defined in section 4), and the content // * field of the EncapsulatedContentInfo value MUST be omitted." // *///from www . j av a 2 s . c o m // if (encapsulate) { // throw new IllegalArgumentException("no signers, encapsulate must be false"); // } if (!DATA.equals(eContentType)) { // throw new IllegalArgumentException("no signers, eContentType must be id-data"); // } // } // if (!DATA.equals(eContentType)) { // /* RFC 3852 5.3 // * [The 'signedAttrs']... // * field is optional, but it MUST be present if the content type of // * the EncapsulatedContentInfo value being signed is not id-data. // */ // // TODO signedAttrs must be present for all signers // } ASN1EncodableVector digestAlgs = new ASN1EncodableVector(); ASN1EncodableVector signerInfos = new ASN1EncodableVector(); digests.clear(); // clear the current preserved digest state Iterator it = _signers.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); digestAlgs.add(CMSUtils.fixAlgID(signer.getDigestAlgorithmID())); signerInfos.add(signer.toSignerInfo()); } boolean isCounterSignature = (eContentType == null); ASN1ObjectIdentifier contentTypeOID = isCounterSignature ? CMSObjectIdentifiers.data : new ASN1ObjectIdentifier(eContentType); it = signerInfs.iterator(); while (it.hasNext()) { SignerInf signer = (SignerInf) it.next(); log.info("signer.signerIdentifier: " + signer.signerIdentifier.toASN1Object().toString()); digestAlgs.add(signer.getDigestAlgorithmID()); signerInfos.add(signer.toSignerInfo(contentTypeOID, content, rand, null, addDefaultAttributes, isCounterSignature)); } ASN1Set certificates = null; if (!certs.isEmpty()) certificates = CMSUtils.createBerSetFromList(certs); ASN1Set certrevlist = null; if (!crls.isEmpty()) certrevlist = CMSUtils.createBerSetFromList(crls); ASN1OctetString octs = null; if (encapsulate && content != null) { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); content.write(bOut); octs = new BERConstructedOctetString(bOut.toByteArray()); } ContentInfo encInfo = new ContentInfo(contentTypeOID, octs); SignedData sd = new SignedData(new DERSet(digestAlgs), encInfo, certificates, certrevlist, new DERSet(signerInfos)); ContentInfo contentInfo = new ContentInfo(CMSObjectIdentifiers.signedData, sd); return new CMSSignedData(content, contentInfo); }