List of usage examples for org.bouncycastle.asn1.cms AttributeTable AttributeTable
public AttributeTable(Attributes attrs)
From source file:CreateSignature.java
License:Apache License
/** * We are extending CMS Signature/* ww w. j ava 2 s . co m*/ * * @param signer information about signer * @return information about SignerInformation */ private SignerInformation signTimeStamp(SignerInformation signer) throws IOException, TSPException { AttributeTable unsignedAttributes = signer.getUnsignedAttributes(); ASN1EncodableVector vector = new ASN1EncodableVector(); if (unsignedAttributes != null) { vector = unsignedAttributes.toASN1EncodableVector(); } byte[] token = getTsaClient().getTimeStampToken(signer.getSignature()); ASN1ObjectIdentifier oid = PKCSObjectIdentifiers.id_aa_signatureTimeStampToken; ASN1Encodable signatureTimeStamp = new Attribute(oid, new DERSet(ASN1Primitive.fromByteArray(token))); vector.add(signatureTimeStamp); Attributes signedAttributes = new Attributes(vector); SignerInformation newSigner = SignerInformation.replaceUnsignedAttributes(signer, new AttributeTable(signedAttributes)); // TODO can this actually happen? if (newSigner == null) { return signer; } return newSigner; }
From source file:br.gov.frameworkdemoiselle.certificate.signer.pkcs7.bc.CAdESSigner.java
License:Open Source License
private AttributeTable mountAttributeTable(Collection<Attribute> collection) { if (collection == null || collection.isEmpty()) { return null; }/*from w w w. ja v a 2s .co m*/ AttributeTable table = null; Hashtable<DERObjectIdentifier, org.bouncycastle.asn1.cms.Attribute> attributes = new Hashtable<DERObjectIdentifier, org.bouncycastle.asn1.cms.Attribute>(); for (Attribute attribute : collection) { org.bouncycastle.asn1.cms.Attribute bcAttribute = this.transformAttribute(attribute); attributes.put(bcAttribute.getAttrType(), bcAttribute); } if (attributes.size() > 0) { table = new AttributeTable(attributes); } return table; }
From source file:br.gov.jfrj.siga.cd.TimeStamper.java
License:Open Source License
/** * Modyfy PKCS#7 data by adding timestamp * // ww w.j a v a2s . c om * (at) param signedData (at) throws Exception */ public static CMSSignedData addTimestamp(CMSSignedData signedData) throws Exception { Collection ss = signedData.getSignerInfos().getSigners(); SignerInformation si = (SignerInformation) ss.iterator().next(); TimeStampToken tok = getTimeStampToken(si.getSignature()); // CertStore certs = tok.getCertificatesAndCRLs("Collection", "BC"); Store certs = tok.getCertificates(); Store certsAndCrls = AssinaturaDigital.buscarCrlParaCadaCertificado(certs); CMSSignedData cmssdcrl = CMSSignedData.replaceCertificatesAndCRLs(tok.toCMSSignedData(), certsAndCrls, certsAndCrls, certsAndCrls); tok = new TimeStampToken(cmssdcrl); ASN1InputStream asn1InputStream = new ASN1InputStream(tok.getEncoded()); ASN1Primitive tstDER = asn1InputStream.readObject(); DERSet ds = new DERSet(tstDER); Attribute a = new Attribute(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken, ds); ASN1EncodableVector dv = new ASN1EncodableVector(); dv.add(a); AttributeTable at = new AttributeTable(dv); si = SignerInformation.replaceUnsignedAttributes(si, at); ss.clear(); ss.add(si); SignerInformationStore sis = new SignerInformationStore(ss); signedData = CMSSignedData.replaceSigners(signedData, sis); return signedData; }
From source file:br.ufpb.dicomflow.integrationAPI.mail.AbstractMailSender.java
License:Open Source License
private Message signAndEcrypt(Message message, X509Certificate signCert, X509Certificate encryptCert, PrivateKey privateKey) throws Exception { MailcapCommandMap mailcap = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); mailcap.addMailcap(/*from ww w . j a v a 2s. c om*/ "application/pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_signature"); mailcap.addMailcap( "application/pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_mime"); mailcap.addMailcap( "application/x-pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_signature"); mailcap.addMailcap( "application/x-pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_mime"); mailcap.addMailcap( "multipart/signed;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.multipart_signed"); CommandMap.setDefaultCommandMap(mailcap); /* Create the Signer - SMIMESignedGenerator */ SMIMECapabilityVector capabilities = new SMIMECapabilityVector(); capabilities.addCapability(SMIMECapability.dES_EDE3_CBC); capabilities.addCapability(SMIMECapability.rC2_CBC, 128); capabilities.addCapability(SMIMECapability.dES_CBC); ASN1EncodableVector attributes = new ASN1EncodableVector(); attributes.add(new SMIMEEncryptionKeyPreferenceAttribute( new IssuerAndSerialNumber(new X500Name(((X509Certificate) signCert).getIssuerDN().getName()), ((X509Certificate) signCert).getSerialNumber()))); attributes.add(new SMIMECapabilitiesAttribute(capabilities)); SMIMESignedGenerator signer = new SMIMESignedGenerator(); signer.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder() .setSignedAttributeGenerator(new AttributeTable(attributes)) .build("DSA".equals(privateKey.getAlgorithm()) ? "SHA1withDSA" : "MD5withRSA", privateKey, signCert)); /* Add the list of certs to the generator */ List certList = new ArrayList(); certList.add(signCert); Store certs = new JcaCertStore(certList); signer.addCertificates(certs); /* Sign the message */ MimeMultipart mm = signer.generate((MimeMessage) message); MimeMessage signedMessage = new MimeMessage(message.getSession()); /* Set all original MIME headers in the signed message */ Enumeration headers = ((MimeMessage) message).getAllHeaderLines(); while (headers.hasMoreElements()) { signedMessage.addHeaderLine((String) headers.nextElement()); } /* Set the content of the signed message */ signedMessage.setContent(mm); signedMessage.saveChanges(); /* Create the encrypter - SMIMEEnvelopedGenerator */ SMIMEEnvelopedGenerator encrypter = new SMIMEEnvelopedGenerator(); encrypter.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(encryptCert)); /* Encrypt the message */ MimeBodyPart encryptedPart = encrypter.generate(signedMessage, new JceCMSContentEncryptorBuilder(CMSAlgorithm.RC2_CBC).build()); /* * Create a new MimeMessage that contains the encrypted and signed * content */ ByteArrayOutputStream out = new ByteArrayOutputStream(); encryptedPart.writeTo(out); MimeMessage encryptedMessage = new MimeMessage(message.getSession(), new ByteArrayInputStream(out.toByteArray())); /* Set all original MIME headers in the encrypted message */ headers = ((MimeMessage) message).getAllHeaderLines(); while (headers.hasMoreElements()) { String headerLine = (String) headers.nextElement(); /* * Make sure not to override any content-* headers from the * original message */ if (!Strings.toLowerCase(headerLine).startsWith("content-")) { encryptedMessage.addHeaderLine(headerLine); } } return encryptedMessage; }
From source file:chapter9.SignedMailExample.java
/** * * @param key/* w w w .j a va 2 s. c om*/ * @param cert * @param certsAndCRLs * @param dataPart * @return * @throws Exception */ public static MimeMultipart createMultipartWithSignature(PrivateKey key, X509Certificate cert, CertStore certsAndCRLs, MimeBodyPart dataPart) throws Exception { //1.- Create some smime capabilities in case someone wants to respond ASN1EncodableVector signedAttrs = new ASN1EncodableVector(); SMIMECapabilityVector caps = new SMIMECapabilityVector(); caps.addCapability(SMIMECapability.aES256_CBC); caps.addCapability(SMIMECapability.dES_EDE3_CBC); caps.addCapability(SMIMECapability.rC2_CBC, 128); signedAttrs.add(new SMIMECapabilitiesAttribute(caps)); signedAttrs.add(new SMIMEEncryptionKeyPreferenceAttribute(SMIMEUtil.createIssuerAndSerialNumberFor(cert))); //2.- Set up the generator SMIMESignedGenerator gen = new SMIMESignedGenerator(); gen.addSigner(key, cert, SMIMESignedGenerator.DIGEST_SHA256, new AttributeTable(signedAttrs), null); gen.addCertificatesAndCRLs(certsAndCRLs); //3.- Create the signed message return gen.generate(dataPart, CryptoDefs.Provider.BC.getName()); }
From source file:com.cordys.coe.ac.emailio.outbound.EmailMessageFactory.java
License:Apache License
/** * This method creates and returns a signed version of the given mail. * * @param mbpToBeSigned The message to sign. * @param eicConfiguration The configuration to use. * @param sSession The main session to use. * @param sSenderAddress The email address of the sender. * * @return The signed message to return. * * @throws OutboundEmailException In case of any exceptions. * @throws KeyManagerException In case of any key manager related exceptions. *///w ww.java2 s .co m private static MimeMessage signMessage(MimeMessage mbpToBeSigned, ISMIMEConfiguration eicConfiguration, Session sSession, String sSenderAddress) throws OutboundEmailException, KeyManagerException { MimeMessage mmReturn = null; // Use the address to find the proper private key. PrivateKey pkKey = null; ICertificateInfo ciInfo = eicConfiguration.getCertificateInfo(sSenderAddress); if (ciInfo != null) { pkKey = ciInfo.getKey(); } if ((pkKey == null) && !eicConfiguration.getBypassSMIME()) { throw new OutboundEmailException( OutboundEmailExceptionMessages.OEE_COULD_NOT_FIND_A_PRIVATE_KEY_FOR_EMAIL_ADDRESS_0, sSenderAddress); } else { mmReturn = mbpToBeSigned; } // Create the signed message if possible. If no private key was found and bypassing S/MIME // is allowed the original message is returned. if (pkKey != null) { try { // Get the public key. X509Certificate xcPublic = ciInfo.getX509Certificate(); // Create the SMIME capabilities SMIMECapabilityVector capabilities = new SMIMECapabilityVector(); capabilities.addCapability(SMIMECapability.dES_EDE3_CBC); capabilities.addCapability(SMIMECapability.rC2_CBC, 128); capabilities.addCapability(SMIMECapability.dES_CBC); // Create the signing preferences. ASN1EncodableVector attributes = new ASN1EncodableVector(); X509Name name = new X509Name(xcPublic.getIssuerDN().getName()); IssuerAndSerialNumber issuerAndSerialNumber = new IssuerAndSerialNumber(name, xcPublic.getSerialNumber()); SMIMEEncryptionKeyPreferenceAttribute encryptionKeyPreferenceAttribute = new SMIMEEncryptionKeyPreferenceAttribute( issuerAndSerialNumber); attributes.add(encryptionKeyPreferenceAttribute); attributes.add(new SMIMECapabilitiesAttribute(capabilities)); // Create the signature generator. SMIMESignedGenerator signer = new SMIMESignedGenerator(); signer.addSigner(pkKey, xcPublic, "DSA".equals(pkKey.getAlgorithm()) ? SMIMESignedGenerator.DIGEST_SHA1 : SMIMESignedGenerator.DIGEST_MD5, new AttributeTable(attributes), null); // Create the list of certificates that will be sent along with the signature. Right // now the CA certificate will NOT be sent along with the mail. It is expected that // the receiver is capable of verifying the authenticity of the certificate itself. List<X509Certificate> certList = new ArrayList<X509Certificate>(); certList.add(xcPublic); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); signer.addCertificatesAndCRLs(certs); // Sign the actual message // The message that was created will ALWAYS have a multipart. In order to keep it // readable in ALL clients we will sign the content of the message, not the whole // message. MimeMultipart mm = signer.generate(mbpToBeSigned, "BC"); mmReturn = new MimeMessage(sSession); // Set the content of the signed message mmReturn.setContent(mm); mmReturn.saveChanges(); } catch (Exception e) { throw new OutboundEmailException(e, OutboundEmailExceptionMessages.OEE_ERROR_SIGNING_EMAIL_MESSAGE); } } else if (LOG.isDebugEnabled()) { LOG.debug("Bypassing S/MIME because no private key was found for " + sSenderAddress); } return mmReturn; }
From source file:com.cordys.coe.test.smime.TestSendEncryptedAndSignedMessage.java
License:Apache License
/** * This method sends the message to the receiver. * * @throws Exception DOCUMENTME// w w w.j a v a 2s .c o m */ private void sendMessage() throws Exception { final InternetAddress[] RECEIVER_ADDRESS = new InternetAddress[] { new InternetAddress("outlook2007@ces70.cordys.com", "Outlook 2007 User"), new InternetAddress("outlookexpress@ces70.cordys.com", "Outlook Express User"), new InternetAddress("thunderbird@ces70.cordys.com", "Thunderbird User"), new InternetAddress("cordystestuser1@ces70.cordys.com", "Cordys Test User 1"), new InternetAddress("cordystestuser2@ces70.cordys.com", "Cordys Test User 2") }; final InternetAddress SENDER_ADDRESS = new InternetAddress("testprogram@ces70.cordys.com", "Test Program User"); String sSubject = "From test progam V1 [S&E] No r"; boolean bDoEncryption = true; // String sContent = "Single line"+System.getProperty("line.separator")+"SecondLine"; String sContent = "Single line\nSecondLine"; // Add capabilities. MailcapCommandMap mailcap = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); mailcap.addMailcap( "application/pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_signature"); mailcap.addMailcap( "application/pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_mime"); mailcap.addMailcap( "application/x-pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_signature"); mailcap.addMailcap( "application/x-pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_mime"); mailcap.addMailcap( "multipart/signed;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.multipart_signed"); CommandMap.setDefaultCommandMap(mailcap); /* Add BC */ Security.addProvider(new BouncyCastleProvider()); /* Get the private key to sign the message with */ ICertificateInfo certInfo = m_km.getCertificateInfo(SENDER_ADDRESS.getAddress()); if (certInfo == null) { throw new Exception("cannot find private key for email address " + SENDER_ADDRESS); } /* Create the message to sign and encrypt */ Properties props = System.getProperties(); props.put("mail.smtp.host", "srv-nl-ces70"); Session session = Session.getDefaultInstance(props, null); MimeMessage body = new MimeMessage(session); body.setContent(sContent, "text/plain"); body.saveChanges(); /* Create the SMIMESignedGenerator */ SMIMECapabilityVector capabilities = new SMIMECapabilityVector(); capabilities.addCapability(SMIMECapability.dES_EDE3_CBC); capabilities.addCapability(SMIMECapability.rC2_CBC, 128); capabilities.addCapability(SMIMECapability.dES_CBC); X509Certificate cert = certInfo.getX509Certificate(); ASN1EncodableVector attributes = new ASN1EncodableVector(); X509Name name = new X509Name(cert.getIssuerDN().getName()); IssuerAndSerialNumber issuerAndSerialNumber = new IssuerAndSerialNumber(name, cert.getSerialNumber()); SMIMEEncryptionKeyPreferenceAttribute encryptionKeyPreferenceAttribute = new SMIMEEncryptionKeyPreferenceAttribute( issuerAndSerialNumber); attributes.add(encryptionKeyPreferenceAttribute); attributes.add(new SMIMECapabilitiesAttribute(capabilities)); SMIMESignedGenerator signer = new SMIMESignedGenerator(); signer.addSigner((PrivateKey) certInfo.getKey(), cert, "DSA".equals(certInfo.getKey().getAlgorithm()) ? SMIMESignedGenerator.DIGEST_SHA1 : SMIMESignedGenerator.DIGEST_MD5, new AttributeTable(attributes), null); /* Add the list of certs to the generator */ List<X509Certificate> certList = new ArrayList<X509Certificate>(); certList.add(cert); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); signer.addCertificatesAndCRLs(certs); /* Sign the message */ MimeMultipart mm = signer.generate(body, "BC"); MimeMessage signedMessage = new MimeMessage(session); /* Set the content of the signed message */ signedMessage.setContent(mm); signedMessage.saveChanges(); /* Create the encrypter */ if (bDoEncryption) { SMIMEEnvelopedGenerator encrypter = new SMIMEEnvelopedGenerator(); for (InternetAddress ia : RECEIVER_ADDRESS) { ICertificateInfo ciTemp = m_km.getCertificateInfo(ia.getAddress()); if (ciTemp != null) { encrypter.addKeyTransRecipient(ciTemp.getX509Certificate()); } else if (LOG.isDebugEnabled()) { LOG.debug("No certificate found for " + ia.toString()); } } /* Encrypt the message */ MimeBodyPart encryptedPart = encrypter.generate(signedMessage, SMIMEEnvelopedGenerator.DES_EDE3_CBC, "BC"); /* * Create a new MimeMessage that contains the encrypted and signed content */ ByteArrayOutputStream out = new ByteArrayOutputStream(); encryptedPart.writeTo(out); body = new MimeMessage(session, new ByteArrayInputStream(out.toByteArray())); } else { body = signedMessage; } body.setFrom(SENDER_ADDRESS); body.setRecipients(Message.RecipientType.TO, RECEIVER_ADDRESS); body.addRecipient(Message.RecipientType.TO, new InternetAddress("intermediate@ces70.cordys.com", "Intermediate user")); body.setSentDate(new Date()); body.addHeader("User-Agent", "CordysMailClient"); body.setSubject(sSubject); Transport.send(body); }
From source file:com.itextpdf.signatures.PdfPKCS7.java
License:Open Source License
/** * Use this constructor if you want to verify a signature. * * @param contentsKey the /Contents key * @param filterSubtype the filtersubtype * @param provider the provider or <code>null</code> for the default provider *//*from w ww.j a va 2s . com*/ @SuppressWarnings({ "unchecked" }) public PdfPKCS7(byte[] contentsKey, PdfName filterSubtype, String provider) { this.filterSubtype = filterSubtype; isTsp = PdfName.ETSI_RFC3161.equals(filterSubtype); isCades = PdfName.ETSI_CAdES_DETACHED.equals(filterSubtype); try { this.provider = provider; ASN1InputStream din = new ASN1InputStream(new ByteArrayInputStream(contentsKey)); // // Basic checks to make sure it's a PKCS#7 SignedData Object // ASN1Primitive pkcs; try { pkcs = din.readObject(); } catch (IOException e) { throw new IllegalArgumentException(PdfException.CannotDecodePkcs7SigneddataObject); } if (!(pkcs instanceof ASN1Sequence)) { throw new IllegalArgumentException(PdfException.NotAValidPkcs7ObjectNotASequence); } ASN1Sequence signedData = (ASN1Sequence) pkcs; ASN1ObjectIdentifier objId = (ASN1ObjectIdentifier) signedData.getObjectAt(0); if (!objId.getId().equals(SecurityIDs.ID_PKCS7_SIGNED_DATA)) throw new IllegalArgumentException(PdfException.NotAValidPkcs7ObjectNotSignedData); ASN1Sequence content = (ASN1Sequence) ((ASN1TaggedObject) signedData.getObjectAt(1)).getObject(); // the positions that we care are: // 0 - version // 1 - digestAlgorithms // 2 - possible ID_PKCS7_DATA // (the certificates and crls are taken out by other means) // last - signerInfos // the version version = ((ASN1Integer) content.getObjectAt(0)).getValue().intValue(); // the digestAlgorithms digestalgos = new HashSet<>(); Enumeration e = ((ASN1Set) content.getObjectAt(1)).getObjects(); while (e.hasMoreElements()) { ASN1Sequence s = (ASN1Sequence) e.nextElement(); ASN1ObjectIdentifier o = (ASN1ObjectIdentifier) s.getObjectAt(0); digestalgos.add(o.getId()); } // the possible ID_PKCS7_DATA ASN1Sequence rsaData = (ASN1Sequence) content.getObjectAt(2); if (rsaData.size() > 1) { ASN1OctetString rsaDataContent = (ASN1OctetString) ((ASN1TaggedObject) rsaData.getObjectAt(1)) .getObject(); RSAdata = rsaDataContent.getOctets(); } int next = 3; while (content.getObjectAt(next) instanceof ASN1TaggedObject) ++next; // the certificates /* This should work, but that's not always the case because of a bug in BouncyCastle: */ certs = SignUtils.readAllCerts(contentsKey); /* The following workaround was provided by Alfonso Massa, but it doesn't always work either. ASN1Set certSet = null; ASN1Set crlSet = null; while (content.getObjectAt(next) instanceof ASN1TaggedObject) { ASN1TaggedObject tagged = (ASN1TaggedObject)content.getObjectAt(next); switch (tagged.getTagNo()) { case 0: certSet = ASN1Set.getInstance(tagged, false); break; case 1: crlSet = ASN1Set.getInstance(tagged, false); break; default: throw new IllegalArgumentException("unknown tag value " + tagged.getTagNo()); } ++next; } certs = new ArrayList<Certificate>(certSet.size()); CertificateFactory certFact = CertificateFactory.getInstance("X.509", new BouncyCastleProvider()); for (Enumeration en = certSet.getObjects(); en.hasMoreElements();) { ASN1Primitive obj = ((ASN1Encodable)en.nextElement()).toASN1Primitive(); if (obj instanceof ASN1Sequence) { ByteArrayInputStream stream = new ByteArrayInputStream(obj.getEncoded()); X509Certificate x509Certificate = (X509Certificate)certFact.generateCertificate(stream); stream.close(); certs.add(x509Certificate); } } */ // the signerInfos ASN1Set signerInfos = (ASN1Set) content.getObjectAt(next); if (signerInfos.size() != 1) throw new IllegalArgumentException( PdfException.ThisPkcs7ObjectHasMultipleSignerinfosOnlyOneIsSupportedAtThisTime); ASN1Sequence signerInfo = (ASN1Sequence) signerInfos.getObjectAt(0); // the positions that we care are // 0 - version // 1 - the signing certificate issuer and serial number // 2 - the digest algorithm // 3 or 4 - digestEncryptionAlgorithm // 4 or 5 - encryptedDigest signerversion = ((ASN1Integer) signerInfo.getObjectAt(0)).getValue().intValue(); // Get the signing certificate ASN1Sequence issuerAndSerialNumber = (ASN1Sequence) signerInfo.getObjectAt(1); X509Principal issuer = SignUtils.getIssuerX509Name(issuerAndSerialNumber); BigInteger serialNumber = ((ASN1Integer) issuerAndSerialNumber.getObjectAt(1)).getValue(); for (Object element : certs) { X509Certificate cert = (X509Certificate) element; if (cert.getIssuerDN().equals(issuer) && serialNumber.equals(cert.getSerialNumber())) { signCert = cert; break; } } if (signCert == null) { throw new PdfException(PdfException.CannotFindSigningCertificateWithSerial1) .setMessageParams(issuer.getName() + " / " + serialNumber.toString(16)); } signCertificateChain(); digestAlgorithmOid = ((ASN1ObjectIdentifier) ((ASN1Sequence) signerInfo.getObjectAt(2)).getObjectAt(0)) .getId(); next = 3; boolean foundCades = false; if (signerInfo.getObjectAt(next) instanceof ASN1TaggedObject) { ASN1TaggedObject tagsig = (ASN1TaggedObject) signerInfo.getObjectAt(next); ASN1Set sseq = ASN1Set.getInstance(tagsig, false); sigAttr = sseq.getEncoded(); // maybe not necessary, but we use the following line as fallback: sigAttrDer = sseq.getEncoded(ASN1Encoding.DER); for (int k = 0; k < sseq.size(); ++k) { ASN1Sequence seq2 = (ASN1Sequence) sseq.getObjectAt(k); String idSeq2 = ((ASN1ObjectIdentifier) seq2.getObjectAt(0)).getId(); if (idSeq2.equals(SecurityIDs.ID_MESSAGE_DIGEST)) { ASN1Set set = (ASN1Set) seq2.getObjectAt(1); digestAttr = ((ASN1OctetString) set.getObjectAt(0)).getOctets(); } else if (idSeq2.equals(SecurityIDs.ID_ADBE_REVOCATION)) { ASN1Set setout = (ASN1Set) seq2.getObjectAt(1); ASN1Sequence seqout = (ASN1Sequence) setout.getObjectAt(0); for (int j = 0; j < seqout.size(); ++j) { ASN1TaggedObject tg = (ASN1TaggedObject) seqout.getObjectAt(j); if (tg.getTagNo() == 0) { ASN1Sequence seqin = (ASN1Sequence) tg.getObject(); findCRL(seqin); } if (tg.getTagNo() == 1) { ASN1Sequence seqin = (ASN1Sequence) tg.getObject(); findOcsp(seqin); } } } else if (isCades && idSeq2.equals(SecurityIDs.ID_AA_SIGNING_CERTIFICATE_V1)) { ASN1Set setout = (ASN1Set) seq2.getObjectAt(1); ASN1Sequence seqout = (ASN1Sequence) setout.getObjectAt(0); SigningCertificate sv2 = SigningCertificate.getInstance(seqout); ESSCertID[] cerv2m = sv2.getCerts(); ESSCertID cerv2 = cerv2m[0]; byte[] enc2 = signCert.getEncoded(); MessageDigest m2 = SignUtils.getMessageDigest("SHA-1"); byte[] signCertHash = m2.digest(enc2); byte[] hs2 = cerv2.getCertHash(); if (!Arrays.equals(signCertHash, hs2)) throw new IllegalArgumentException( "Signing certificate doesn't match the ESS information."); foundCades = true; } else if (isCades && idSeq2.equals(SecurityIDs.ID_AA_SIGNING_CERTIFICATE_V2)) { ASN1Set setout = (ASN1Set) seq2.getObjectAt(1); ASN1Sequence seqout = (ASN1Sequence) setout.getObjectAt(0); SigningCertificateV2 sv2 = SigningCertificateV2.getInstance(seqout); ESSCertIDv2[] cerv2m = sv2.getCerts(); ESSCertIDv2 cerv2 = cerv2m[0]; AlgorithmIdentifier ai2 = cerv2.getHashAlgorithm(); byte[] enc2 = signCert.getEncoded(); MessageDigest m2 = SignUtils .getMessageDigest(DigestAlgorithms.getDigest(ai2.getAlgorithm().getId())); byte[] signCertHash = m2.digest(enc2); byte[] hs2 = cerv2.getCertHash(); if (!Arrays.equals(signCertHash, hs2)) throw new IllegalArgumentException( "Signing certificate doesn't match the ESS information."); foundCades = true; } } if (digestAttr == null) throw new IllegalArgumentException(PdfException.AuthenticatedAttributeIsMissingTheDigest); ++next; } if (isCades && !foundCades) throw new IllegalArgumentException("CAdES ESS information missing."); digestEncryptionAlgorithmOid = ((ASN1ObjectIdentifier) ((ASN1Sequence) signerInfo.getObjectAt(next++)) .getObjectAt(0)).getId(); digest = ((ASN1OctetString) signerInfo.getObjectAt(next++)).getOctets(); if (next < signerInfo.size() && signerInfo.getObjectAt(next) instanceof ASN1TaggedObject) { ASN1TaggedObject taggedObject = (ASN1TaggedObject) signerInfo.getObjectAt(next); ASN1Set unat = ASN1Set.getInstance(taggedObject, false); AttributeTable attble = new AttributeTable(unat); Attribute ts = attble.get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken); if (ts != null && ts.getAttrValues().size() > 0) { ASN1Set attributeValues = ts.getAttrValues(); ASN1Sequence tokenSequence = ASN1Sequence.getInstance(attributeValues.getObjectAt(0)); org.bouncycastle.asn1.cms.ContentInfo contentInfo = org.bouncycastle.asn1.cms.ContentInfo .getInstance(tokenSequence); this.timeStampToken = new TimeStampToken(contentInfo); } } if (isTsp) { org.bouncycastle.asn1.cms.ContentInfo contentInfoTsp = org.bouncycastle.asn1.cms.ContentInfo .getInstance(signedData); this.timeStampToken = new TimeStampToken(contentInfoTsp); TimeStampTokenInfo info = timeStampToken.getTimeStampInfo(); String algOID = info.getHashAlgorithm().getAlgorithm().getId(); messageDigest = DigestAlgorithms.getMessageDigestFromOid(algOID, null); } else { if (RSAdata != null || digestAttr != null) { if (PdfName.Adbe_pkcs7_sha1.equals(getFilterSubtype())) { messageDigest = DigestAlgorithms.getMessageDigest("SHA1", provider); } else { messageDigest = DigestAlgorithms.getMessageDigest(getHashAlgorithm(), provider); } encContDigest = DigestAlgorithms.getMessageDigest(getHashAlgorithm(), provider); } sig = initSignature(signCert.getPublicKey()); } } catch (Exception e) { throw new PdfException(e); } }
From source file:com.itextpdf.text.pdf.PdfPKCS7.java
License:Open Source License
/** * Verifies a signature using the sub-filter adbe.pkcs7.detached or * adbe.pkcs7.sha1./*from w w w . j av a 2 s .c o m*/ * @param contentsKey the /Contents key * @param provider the provider or <code>null</code> for the default provider */ @SuppressWarnings("unchecked") public PdfPKCS7(byte[] contentsKey, String provider) { try { this.provider = provider; ASN1InputStream din = new ASN1InputStream(new ByteArrayInputStream(contentsKey)); // // Basic checks to make sure it's a PKCS#7 SignedData Object // DERObject pkcs; try { pkcs = din.readObject(); } catch (IOException e) { throw new IllegalArgumentException( MessageLocalization.getComposedMessage("can.t.decode.pkcs7signeddata.object")); } if (!(pkcs instanceof ASN1Sequence)) { throw new IllegalArgumentException( MessageLocalization.getComposedMessage("not.a.valid.pkcs.7.object.not.a.sequence")); } ASN1Sequence signedData = (ASN1Sequence) pkcs; DERObjectIdentifier objId = (DERObjectIdentifier) signedData.getObjectAt(0); if (!objId.getId().equals(ID_PKCS7_SIGNED_DATA)) throw new IllegalArgumentException( MessageLocalization.getComposedMessage("not.a.valid.pkcs.7.object.not.signed.data")); ASN1Sequence content = (ASN1Sequence) ((DERTaggedObject) signedData.getObjectAt(1)).getObject(); // the positions that we care are: // 0 - version // 1 - digestAlgorithms // 2 - possible ID_PKCS7_DATA // (the certificates and crls are taken out by other means) // last - signerInfos // the version version = ((DERInteger) content.getObjectAt(0)).getValue().intValue(); // the digestAlgorithms digestalgos = new HashSet<String>(); Enumeration<ASN1Sequence> e = ((ASN1Set) content.getObjectAt(1)).getObjects(); while (e.hasMoreElements()) { ASN1Sequence s = e.nextElement(); DERObjectIdentifier o = (DERObjectIdentifier) s.getObjectAt(0); digestalgos.add(o.getId()); } // the certificates X509CertParser cr = new X509CertParser(); cr.engineInit(new ByteArrayInputStream(contentsKey)); certs = cr.engineReadAll(); // the possible ID_PKCS7_DATA ASN1Sequence rsaData = (ASN1Sequence) content.getObjectAt(2); if (rsaData.size() > 1) { DEROctetString rsaDataContent = (DEROctetString) ((DERTaggedObject) rsaData.getObjectAt(1)) .getObject(); RSAdata = rsaDataContent.getOctets(); } // the signerInfos int next = 3; while (content.getObjectAt(next) instanceof DERTaggedObject) ++next; ASN1Set signerInfos = (ASN1Set) content.getObjectAt(next); if (signerInfos.size() != 1) throw new IllegalArgumentException(MessageLocalization.getComposedMessage( "this.pkcs.7.object.has.multiple.signerinfos.only.one.is.supported.at.this.time")); ASN1Sequence signerInfo = (ASN1Sequence) signerInfos.getObjectAt(0); // the positions that we care are // 0 - version // 1 - the signing certificate issuer and serial number // 2 - the digest algorithm // 3 or 4 - digestEncryptionAlgorithm // 4 or 5 - encryptedDigest signerversion = ((DERInteger) signerInfo.getObjectAt(0)).getValue().intValue(); // Get the signing certificate ASN1Sequence issuerAndSerialNumber = (ASN1Sequence) signerInfo.getObjectAt(1); X509Principal issuer = new X509Principal( issuerAndSerialNumber.getObjectAt(0).getDERObject().getEncoded()); BigInteger serialNumber = ((DERInteger) issuerAndSerialNumber.getObjectAt(1)).getValue(); for (Object element : certs) { X509Certificate cert = (X509Certificate) element; if (issuer.equals(cert.getIssuerDN()) && serialNumber.equals(cert.getSerialNumber())) { signCert = cert; break; } } if (signCert == null) { throw new IllegalArgumentException( MessageLocalization.getComposedMessage("can.t.find.signing.certificate.with.serial.1", issuer.getName() + " / " + serialNumber.toString(16))); } signCertificateChain(); digestAlgorithm = ((DERObjectIdentifier) ((ASN1Sequence) signerInfo.getObjectAt(2)).getObjectAt(0)) .getId(); next = 3; if (signerInfo.getObjectAt(next) instanceof ASN1TaggedObject) { ASN1TaggedObject tagsig = (ASN1TaggedObject) signerInfo.getObjectAt(next); ASN1Set sseq = ASN1Set.getInstance(tagsig, false); sigAttr = sseq.getEncoded(ASN1Encodable.DER); for (int k = 0; k < sseq.size(); ++k) { ASN1Sequence seq2 = (ASN1Sequence) sseq.getObjectAt(k); if (((DERObjectIdentifier) seq2.getObjectAt(0)).getId().equals(ID_MESSAGE_DIGEST)) { ASN1Set set = (ASN1Set) seq2.getObjectAt(1); digestAttr = ((DEROctetString) set.getObjectAt(0)).getOctets(); } else if (((DERObjectIdentifier) seq2.getObjectAt(0)).getId().equals(ID_ADBE_REVOCATION)) { ASN1Set setout = (ASN1Set) seq2.getObjectAt(1); ASN1Sequence seqout = (ASN1Sequence) setout.getObjectAt(0); for (int j = 0; j < seqout.size(); ++j) { ASN1TaggedObject tg = (ASN1TaggedObject) seqout.getObjectAt(j); if (tg.getTagNo() == 0) { ASN1Sequence seqin = (ASN1Sequence) tg.getObject(); findCRL(seqin); } if (tg.getTagNo() == 1) { ASN1Sequence seqin = (ASN1Sequence) tg.getObject(); findOcsp(seqin); } } } } if (digestAttr == null) throw new IllegalArgumentException(MessageLocalization .getComposedMessage("authenticated.attribute.is.missing.the.digest")); ++next; } digestEncryptionAlgorithm = ((DERObjectIdentifier) ((ASN1Sequence) signerInfo.getObjectAt(next++)) .getObjectAt(0)).getId(); digest = ((DEROctetString) signerInfo.getObjectAt(next++)).getOctets(); if (next < signerInfo.size() && signerInfo.getObjectAt(next) instanceof DERTaggedObject) { DERTaggedObject taggedObject = (DERTaggedObject) signerInfo.getObjectAt(next); ASN1Set unat = ASN1Set.getInstance(taggedObject, false); AttributeTable attble = new AttributeTable(unat); Attribute ts = attble.get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken); if (ts != null && ts.getAttrValues().size() > 0) { ASN1Set attributeValues = ts.getAttrValues(); ASN1Sequence tokenSequence = ASN1Sequence.getInstance(attributeValues.getObjectAt(0)); ContentInfo contentInfo = new ContentInfo(tokenSequence); this.timeStampToken = new TimeStampToken(contentInfo); } } if (RSAdata != null || digestAttr != null) { if (provider == null || provider.startsWith("SunPKCS11")) messageDigest = MessageDigest.getInstance(getHashAlgorithm()); else messageDigest = MessageDigest.getInstance(getHashAlgorithm(), provider); } if (provider == null) sig = Signature.getInstance(getDigestAlgorithm()); else sig = Signature.getInstance(getDigestAlgorithm(), provider); sig.initVerify(signCert.getPublicKey()); } catch (Exception e) { throw new ExceptionConverter(e); } }
From source file:com.itextpdf.text.pdf.security.PdfPKCS7.java
License:Open Source License
/** * Use this constructor if you want to verify a signature. * @param contentsKey the /Contents key/*from ww w . ja va 2 s. c om*/ * @param filterSubtype the filtersubtype * @param provider the provider or <code>null</code> for the default provider */ @SuppressWarnings({ "unchecked" }) public PdfPKCS7(byte[] contentsKey, PdfName filterSubtype, String provider) { this.filterSubtype = filterSubtype; isTsp = PdfName.ETSI_RFC3161.equals(filterSubtype); isCades = PdfName.ETSI_CADES_DETACHED.equals(filterSubtype); try { this.provider = provider; ASN1InputStream din = new ASN1InputStream(new ByteArrayInputStream(contentsKey)); // // Basic checks to make sure it's a PKCS#7 SignedData Object // ASN1Primitive pkcs; try { pkcs = din.readObject(); } catch (IOException e) { throw new IllegalArgumentException( MessageLocalization.getComposedMessage("can.t.decode.pkcs7signeddata.object")); } if (!(pkcs instanceof ASN1Sequence)) { throw new IllegalArgumentException( MessageLocalization.getComposedMessage("not.a.valid.pkcs.7.object.not.a.sequence")); } ASN1Sequence signedData = (ASN1Sequence) pkcs; ASN1ObjectIdentifier objId = (ASN1ObjectIdentifier) signedData.getObjectAt(0); if (!objId.getId().equals(SecurityIDs.ID_PKCS7_SIGNED_DATA)) throw new IllegalArgumentException( MessageLocalization.getComposedMessage("not.a.valid.pkcs.7.object.not.signed.data")); ASN1Sequence content = (ASN1Sequence) ((ASN1TaggedObject) signedData.getObjectAt(1)).getObject(); // the positions that we care are: // 0 - version // 1 - digestAlgorithms // 2 - possible ID_PKCS7_DATA // (the certificates and crls are taken out by other means) // last - signerInfos // the version version = ((ASN1Integer) content.getObjectAt(0)).getValue().intValue(); // the digestAlgorithms digestalgos = new HashSet<String>(); Enumeration<ASN1Sequence> e = ((ASN1Set) content.getObjectAt(1)).getObjects(); while (e.hasMoreElements()) { ASN1Sequence s = e.nextElement(); ASN1ObjectIdentifier o = (ASN1ObjectIdentifier) s.getObjectAt(0); digestalgos.add(o.getId()); } // the possible ID_PKCS7_DATA ASN1Sequence rsaData = (ASN1Sequence) content.getObjectAt(2); if (rsaData.size() > 1) { ASN1OctetString rsaDataContent = (ASN1OctetString) ((ASN1TaggedObject) rsaData.getObjectAt(1)) .getObject(); RSAdata = rsaDataContent.getOctets(); } int next = 3; while (content.getObjectAt(next) instanceof ASN1TaggedObject) ++next; // the certificates /* This should work, but that's not always the case because of a bug in BouncyCastle: */ X509CertParser cr = new X509CertParser(); cr.engineInit(new ByteArrayInputStream(contentsKey)); certs = cr.engineReadAll(); /* The following workaround was provided by Alfonso Massa, but it doesn't always work either. ASN1Set certSet = null; ASN1Set crlSet = null; while (content.getObjectAt(next) instanceof ASN1TaggedObject) { ASN1TaggedObject tagged = (ASN1TaggedObject)content.getObjectAt(next); switch (tagged.getTagNo()) { case 0: certSet = ASN1Set.getInstance(tagged, false); break; case 1: crlSet = ASN1Set.getInstance(tagged, false); break; default: throw new IllegalArgumentException("unknown tag value " + tagged.getTagNo()); } ++next; } certs = new ArrayList<Certificate>(certSet.size()); CertificateFactory certFact = CertificateFactory.getInstance("X.509", new BouncyCastleProvider()); for (Enumeration en = certSet.getObjects(); en.hasMoreElements();) { ASN1Primitive obj = ((ASN1Encodable)en.nextElement()).toASN1Primitive(); if (obj instanceof ASN1Sequence) { ByteArrayInputStream stream = new ByteArrayInputStream(obj.getEncoded()); X509Certificate x509Certificate = (X509Certificate)certFact.generateCertificate(stream); stream.close(); certs.add(x509Certificate); } } */ // the signerInfos ASN1Set signerInfos = (ASN1Set) content.getObjectAt(next); if (signerInfos.size() != 1) throw new IllegalArgumentException(MessageLocalization.getComposedMessage( "this.pkcs.7.object.has.multiple.signerinfos.only.one.is.supported.at.this.time")); ASN1Sequence signerInfo = (ASN1Sequence) signerInfos.getObjectAt(0); // the positions that we care are // 0 - version // 1 - the signing certificate issuer and serial number // 2 - the digest algorithm // 3 or 4 - digestEncryptionAlgorithm // 4 or 5 - encryptedDigest signerversion = ((ASN1Integer) signerInfo.getObjectAt(0)).getValue().intValue(); // Get the signing certificate ASN1Sequence issuerAndSerialNumber = (ASN1Sequence) signerInfo.getObjectAt(1); X509Principal issuer = new X509Principal( issuerAndSerialNumber.getObjectAt(0).toASN1Primitive().getEncoded()); BigInteger serialNumber = ((ASN1Integer) issuerAndSerialNumber.getObjectAt(1)).getValue(); for (Object element : certs) { X509Certificate cert = (X509Certificate) element; if (cert.getIssuerDN().equals(issuer) && serialNumber.equals(cert.getSerialNumber())) { signCert = cert; break; } } if (signCert == null) { throw new IllegalArgumentException( MessageLocalization.getComposedMessage("can.t.find.signing.certificate.with.serial.1", issuer.getName() + " / " + serialNumber.toString(16))); } signCertificateChain(); digestAlgorithmOid = ((ASN1ObjectIdentifier) ((ASN1Sequence) signerInfo.getObjectAt(2)).getObjectAt(0)) .getId(); next = 3; boolean foundCades = false; if (signerInfo.getObjectAt(next) instanceof ASN1TaggedObject) { ASN1TaggedObject tagsig = (ASN1TaggedObject) signerInfo.getObjectAt(next); ASN1Set sseq = ASN1Set.getInstance(tagsig, false); sigAttr = sseq.getEncoded(); // maybe not necessary, but we use the following line as fallback: sigAttrDer = sseq.getEncoded(ASN1Encoding.DER); for (int k = 0; k < sseq.size(); ++k) { ASN1Sequence seq2 = (ASN1Sequence) sseq.getObjectAt(k); String idSeq2 = ((ASN1ObjectIdentifier) seq2.getObjectAt(0)).getId(); if (idSeq2.equals(SecurityIDs.ID_MESSAGE_DIGEST)) { ASN1Set set = (ASN1Set) seq2.getObjectAt(1); digestAttr = ((ASN1OctetString) set.getObjectAt(0)).getOctets(); } else if (idSeq2.equals(SecurityIDs.ID_ADBE_REVOCATION)) { ASN1Set setout = (ASN1Set) seq2.getObjectAt(1); ASN1Sequence seqout = (ASN1Sequence) setout.getObjectAt(0); for (int j = 0; j < seqout.size(); ++j) { ASN1TaggedObject tg = (ASN1TaggedObject) seqout.getObjectAt(j); if (tg.getTagNo() == 0) { ASN1Sequence seqin = (ASN1Sequence) tg.getObject(); findCRL(seqin); } if (tg.getTagNo() == 1) { ASN1Sequence seqin = (ASN1Sequence) tg.getObject(); findOcsp(seqin); } } } else if (isCades && idSeq2.equals(SecurityIDs.ID_AA_SIGNING_CERTIFICATE_V1)) { ASN1Set setout = (ASN1Set) seq2.getObjectAt(1); ASN1Sequence seqout = (ASN1Sequence) setout.getObjectAt(0); SigningCertificate sv2 = SigningCertificate.getInstance(seqout); ESSCertID[] cerv2m = sv2.getCerts(); ESSCertID cerv2 = cerv2m[0]; byte[] enc2 = signCert.getEncoded(); MessageDigest m2 = new BouncyCastleDigest().getMessageDigest("SHA-1"); byte[] signCertHash = m2.digest(enc2); byte[] hs2 = cerv2.getCertHash(); if (!Arrays.equals(signCertHash, hs2)) throw new IllegalArgumentException( "Signing certificate doesn't match the ESS information."); foundCades = true; } else if (isCades && idSeq2.equals(SecurityIDs.ID_AA_SIGNING_CERTIFICATE_V2)) { ASN1Set setout = (ASN1Set) seq2.getObjectAt(1); ASN1Sequence seqout = (ASN1Sequence) setout.getObjectAt(0); SigningCertificateV2 sv2 = SigningCertificateV2.getInstance(seqout); ESSCertIDv2[] cerv2m = sv2.getCerts(); ESSCertIDv2 cerv2 = cerv2m[0]; AlgorithmIdentifier ai2 = cerv2.getHashAlgorithm(); byte[] enc2 = signCert.getEncoded(); MessageDigest m2 = new BouncyCastleDigest() .getMessageDigest(DigestAlgorithms.getDigest(ai2.getAlgorithm().getId())); byte[] signCertHash = m2.digest(enc2); byte[] hs2 = cerv2.getCertHash(); if (!Arrays.equals(signCertHash, hs2)) throw new IllegalArgumentException( "Signing certificate doesn't match the ESS information."); foundCades = true; } } if (digestAttr == null) throw new IllegalArgumentException(MessageLocalization .getComposedMessage("authenticated.attribute.is.missing.the.digest")); ++next; } if (isCades && !foundCades) throw new IllegalArgumentException("CAdES ESS information missing."); digestEncryptionAlgorithmOid = ((ASN1ObjectIdentifier) ((ASN1Sequence) signerInfo.getObjectAt(next++)) .getObjectAt(0)).getId(); digest = ((ASN1OctetString) signerInfo.getObjectAt(next++)).getOctets(); if (next < signerInfo.size() && signerInfo.getObjectAt(next) instanceof ASN1TaggedObject) { ASN1TaggedObject taggedObject = (ASN1TaggedObject) signerInfo.getObjectAt(next); ASN1Set unat = ASN1Set.getInstance(taggedObject, false); AttributeTable attble = new AttributeTable(unat); Attribute ts = attble.get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken); if (ts != null && ts.getAttrValues().size() > 0) { ASN1Set attributeValues = ts.getAttrValues(); ASN1Sequence tokenSequence = ASN1Sequence.getInstance(attributeValues.getObjectAt(0)); ContentInfo contentInfo = new ContentInfo(tokenSequence); this.timeStampToken = new TimeStampToken(contentInfo); } } if (isTsp) { ContentInfo contentInfoTsp = new ContentInfo(signedData); this.timeStampToken = new TimeStampToken(contentInfoTsp); TimeStampTokenInfo info = timeStampToken.getTimeStampInfo(); String algOID = info.getMessageImprintAlgOID().getId(); messageDigest = DigestAlgorithms.getMessageDigestFromOid(algOID, null); } else { if (RSAdata != null || digestAttr != null) { if (PdfName.ADBE_PKCS7_SHA1.equals(getFilterSubtype())) { messageDigest = DigestAlgorithms.getMessageDigest("SHA1", provider); } else { messageDigest = DigestAlgorithms.getMessageDigest(getHashAlgorithm(), provider); } encContDigest = DigestAlgorithms.getMessageDigest(getHashAlgorithm(), provider); } sig = initSignature(signCert.getPublicKey()); } } catch (Exception e) { throw new ExceptionConverter(e); } }