List of usage examples for org.bouncycastle.cms CMSSignedData getSignerInfos
public SignerInformationStore getSignerInfos()
From source file:it.treviso.provincia.freesigner.applet.FreeSignerSignApplet3.java
License:Open Source License
/** * Creates the signed data structure, using signer infos precedently * accumulated./*from ww w . j av a 2s . co m*/ * * @return @throws CertStoreException * @throws CertStoreException * @throws InvalidAlgorithmParameterException * @throws CertificateExpiredException * @throws CertificateNotYetValidException * @throws NoSuchAlgorithmException * @throws NoSuchProviderException * @throws CMSException * @throws NoSuchStoreException */ @SuppressWarnings("deprecation") private CMSSignedData buildCMSSignedData() throws CertStoreException, InvalidAlgorithmParameterException, CertificateExpiredException, CertificateNotYetValidException, NoSuchAlgorithmException, NoSuchProviderException, CMSException, NoSuchStoreException { CMSSignedData s = null; CMSSignedData actualFile = null; /** * resign? reads the file and creates a CMSSignedData of the actual File */ if (this.resign) { try { byte[] bytesFromFile = getBytesFromFile(new File(fileDaAprire)); byte[] certData; try { certData = Base64.decode(bytesFromFile); } catch (Exception eb64) { certData = bytesFromFile; } actualFile = new CMSSignedData(certData); } catch (IOException e) { e.printStackTrace(); } } if (this.signersCertList.size() != 0) { // Per passare i certificati al generatore li si incapsula // in un // CertStore. CertStore store = CertStore.getInstance("Collection", new CollectionCertStoreParameters(this.signersCertList), "BC"); log.println("Adding certificates ... "); this.cmsGenerator.addCertificatesAndCRLs(store); // Finalmente, si pu creare il l'oggetto CMS. log.println("Generating CMSSignedData "); s = this.cmsGenerator.generate(this.msg, true); getSignerCN(s); /** * Resigning process: * retrieves: * - SignerInformationStore * - CertStore * - x509Store * first from the actualFile (the one on disk) then from CMSSignedData generated in the previous step. * */ if (resign) { SignerInformationStore actualSigners = actualFile.getSignerInfos(); CertStore existingCerts = actualFile.getCertificatesAndCRLs("Collection", "BC"); X509Store x509Store = actualFile.getAttributeCertificates("Collection", "BC"); CertStore newCerts = s.getCertificatesAndCRLs("Collection", "BC"); X509Store newX509Store = s.getAttributeCertificates("Collection", "BC"); SignerInformationStore newSigners = s.getSignerInfos(); CMSSignedDataGenerator signGen = new CMSSignedDataGenerator(); //add old certs signGen.addCertificatesAndCRLs(existingCerts); //add old certs attributes signGen.addAttributeCertificates(x509Store); //add old signers signGen.addSigners(actualSigners); //add new certs signGen.addCertificatesAndCRLs(newCerts); //add new certs attributes signGen.addAttributeCertificates(newX509Store); //add old signers signGen.addSigners(newSigners); s = signGen.generate(this.msg, true, "BC"); } // Verifica log.println("\nStarting CMSSignedData verification ... "); // recupero dal CMS la lista dei certificati CertStore certs = s.getCertificatesAndCRLs("Collection", "BC"); // Recupero i firmatari. SignerInformationStore signers = s.getSignerInfos(); Collection c = signers.getSigners(); log.println(c.size() + " signers found."); Iterator it = c.iterator(); // ciclo tra tutti i firmatari int i = 0; boolean verified = true; while (it.hasNext() && verified) { SignerInformation signer = (SignerInformation) it.next(); Collection certCollection = certs.getCertificates(signer.getSID()); if (certCollection.size() == 1) { // Iterator certIt = certCollection.iterator(); // X509Certificate cert = (X509Certificate) // certIt.next(); X509Certificate cert = (X509Certificate) certCollection.toArray()[0]; log.println(i + ") Verifiying signature from:\n" + cert.getSubjectDN()); /* * log.println("Certificate follows:"); * log.println("===================================="); * log.println(cert); * log.println("===================================="); */ if (verified = signer.verify(cert, "BC")) { log.println("SIGNATURE " + i + " OK!"); } else { System.err.println("SIGNATURE " + i + " Failure!"); JOptionPane.showMessageDialog(this, "La verifica della firma di:\n" + cert.getSubjectDN() + "\n fallita!", "Costruzione della busta pkcs7 fallita.", JOptionPane.ERROR_MESSAGE); } } else { System.out.println("There is not exactly one certificate for this signer!"); } i++; } if (!verified) s = null; } return s; }
From source file:it.treviso.provincia.freesigner.applet.FreeSignerSignApplet3.java
License:Open Source License
private void getSignerCN(CMSSignedData s) throws NoSuchAlgorithmException, NoSuchProviderException, CMSException, CertStoreException { CertStore certs = s.getCertificatesAndCRLs("Collection", "BC"); SignerInformationStore signers = s.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator();// w ww . j a v a2s. c o m while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); Collection certCollection = certs.getCertificates(signer.getSID()); if (certCollection.size() > 0) { X509Certificate cert = (X509Certificate) certCollection.toArray()[0]; this.signerCN = cert.getSubjectDN().toString(); log.println("FFF signerCN =" + signerCN); } } }
From source file:it.treviso.provincia.freesigner.crl.CLICRLTest.java
License:Open Source License
/** * It recognises all the signers of the CMS (coded base64 or DER) and verify if * it is revoked, if it is signed with the public key of a given CA and if it is * temporally valid<br><br>/*from w w w. ja v a 2s . co m*/ * * Fa un giro tra tutti gli i firmatari del file firmato codificato base64 o * DER e verifica revoca, integrit (+corrispondenza all'insieme delle CA * presenti in root) e scadenza dei rispettivi certificati * * @return true */ public boolean verifica() { X509Certificate cert = null; try { byte[] buffer = new byte[1024]; FileInputStream is = new FileInputStream(filePath); ByteArrayOutputStream baos = new ByteArrayOutputStream(); while (is.read(buffer) > 0) { baos.write(buffer); } byte[] risultato = baos.toByteArray(); //codifica file Base64 o DER? byte[] certData; try { //se Base64, decodifica (italian law!) certData = Base64.decode(risultato); //Decodifica base64 completata System.out.println("Il file firmato in formato Base64"); } catch (Exception e) { // il file non e' in formato base64 //quindi in DER (again italian law!) System.out.println("Il file firmato in formato DER"); certData = risultato; } //Estrazione del certificato dal file (ora codificato DER) CMSSignedData s = new CMSSignedData(certData); Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); //recupero dal CMS la lista dei certificati CertStore certs = s.getCertificatesAndCRLs("Collection", "BC"); //Recupero i firmatari. SignerInformationStore signers = s.getSignerInfos(); Collection c = signers.getSigners(); System.out.println(c.size() + " firmatari diversi trovati"); System.out.println(certs.getCertificates(null).size() + " firmatari diversi trovati"); System.out.println(s.getSignerInfos().size() + " firmatari diversi trovati"); //non avrebbe senso che fossero uguali //quindi fa il ciclo tra i firmatari //PERO' PUO' CAPITARE CHE CI SIA UN FIRMATARIO CHE FIRMA DUE VOLTE // E IN QUESTO CASO DOVREBBE FARE IL GIRO SUI CERTIFICATI!!! Iterator it = c.iterator(); //ciclo tra tutti i firmatari int i = 0; while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); Collection certCollection = certs.getCertificates(signer.getSID()); if (certCollection.size() == 1) { //Iterator certIt = certCollection.iterator(); //X509Certificate cert = (X509Certificate) // certIt.next(); cert = (X509Certificate) certCollection.toArray()[0]; System.out.println(i + ") Verifiying signature from:\n" + cert.getSubjectDN()); /* * System.out.println("Certificate follows:"); * System.out.println("===================================="); * System.out.println(cert); * System.out.println("===================================="); */ //VERIFICA REVOCA // Verifica Revoca e appartenza della CA // NB verifica integrit del doc e non-scadenza del cert sono fatte in CLITest if (CRL.isNotRevoked(cert)) { System.out.println("Certificato non revocato"); } //VERIFICA VALIDITA' TEMPORALE try { cert.checkValidity(); System.out.println("Certificato valido fino a " + cert.getNotAfter()); } catch (CertificateExpiredException ex) { System.out.println("Certificato scaduto il " + cert.getNotAfter()); } catch (CertificateNotYetValidException ex) { System.out.println("Certificato non ancora valido. Valido da " + cert.getNotBefore()); } //VERIFICA INTEGRITA' //verify that the given certificate succesfully handles //and confirms the signature associated with this signer //and, if a signingTime attribute is available, that the //certificate was valid at the time the signature was //generated. if (signer.verify(cert, "BC")) { System.out.println("Firma " + i + " integra."); } else { System.err.println("Firma " + i + " non integra!"); } } else { System.out.println("There is not exactly one certificate for this signer!"); } i++; } } catch (Exception ex) { System.err.println("eEXCEPTION:\n" + ex); } return true; }
From source file:it.treviso.provincia.freesigner.crl.X509CertRL.java
License:Open Source License
/** * Returns certificate present in a file at the given filePath.<br> * This can be coded base64 or DER<br> * <br>/* w w w . ja va 2s .c o m*/ * Restituisce il certificato contenuto nel file specificato nel filePath. * Distingue tra codifica base64 e DER. * * @return certificate * @param filePath * String */ public static X509Certificate getCertificatesFromFile(String filePath) { X509Certificate cert = null; try { byte[] buffer = new byte[1024]; FileInputStream is = new FileInputStream(filePath); ByteArrayOutputStream baos = new ByteArrayOutputStream(); while (is.read(buffer) > 0) { baos.write(buffer); } byte[] risultato = baos.toByteArray(); // codifica file Base64 o DER? byte[] certData; try { // se Base64, decodifica (italian law!) certData = Base64.decode(risultato); // Decodifica base64 completata System.out.println("Il file in formato Base64"); } catch (Exception e) { // il file non e' in formato base64 // quindi in DER (again italian law!) System.out.println("Il file in formato DER"); certData = risultato; } // Estrazione del certificato dal file (ora codificato DER) CMSSignedData s = new CMSSignedData(certData); Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); // recupero dal CMS la lista dei certificati CertStore certs = s.getCertificatesAndCRLs("Collection", "BC"); // Recupero i firmatari. SignerInformationStore signers = s.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); // ciclo tra tutti i firmatari int i = 0; while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); Collection certCollection = certs.getCertificates(signer.getSID()); if (certCollection.size() == 1) { // Iterator certIt = certCollection.iterator(); // X509Certificate cert = (X509Certificate) // certIt.next(); cert = (X509Certificate) certCollection.toArray()[0]; } else { System.out.println("There is not exactly one certificate for this signer!"); } i++; } } catch (Exception ex) { System.err.println("EXCEPTION:\n" + ex); } return cert; }
From source file:known.issues.DSS642.CAdESCounterSignatureTest.java
License:Open Source License
@Test public void test() throws Exception { CertificateService certificateService = new CertificateService(); final MockPrivateKeyEntry entryUserA = certificateService .generateCertificateChain(SignatureAlgorithm.RSA_SHA256); final MockPrivateKeyEntry entryUserB = certificateService .generateCertificateChain(SignatureAlgorithm.RSA_SHA256); DSSDocument document = new FileDocument(new File("src/test/resources/sample.xml")); // Sign/* w w w. j a v a 2 s . c o m*/ CAdESSignatureParameters signatureParameters = new CAdESSignatureParameters(); signatureParameters.setSigningCertificate(entryUserA.getCertificate()); signatureParameters.setCertificateChain(entryUserA.getCertificateChain()); signatureParameters.setSignatureLevel(SignatureLevel.CAdES_BASELINE_B); signatureParameters.setSignaturePackaging(SignaturePackaging.ENVELOPING); CertificateVerifier certificateVerifier = new CommonCertificateVerifier(); CAdESService service = new CAdESService(certificateVerifier); ToBeSigned dataToSign = service.getDataToSign(document, signatureParameters); SignatureValue signatureValue = sign(signatureParameters.getSignatureAlgorithm(), entryUserA, dataToSign); DSSDocument signedDocument = service.signDocument(document, signatureParameters, signatureValue); // Countersign final InputStream inputStream = signedDocument.openStream(); final CMSSignedData cmsSignedData = new CMSSignedData(inputStream); IOUtils.closeQuietly(inputStream); SignerInformationStore signerInfosStore = cmsSignedData.getSignerInfos(); Collection<SignerInformation> signerInfos = signerInfosStore.getSigners(); assertEquals(1, signerInfos.size()); SignerInformation signerInfo = signerInfos.iterator().next(); Thread.sleep(1000); CAdESSignatureParameters countersigningParameters = new CAdESSignatureParameters(); countersigningParameters.setSignatureLevel(SignatureLevel.CAdES_BASELINE_B); countersigningParameters.setSignaturePackaging(SignaturePackaging.ENVELOPING); countersigningParameters.setSigningCertificate(entryUserB.getCertificate()); countersigningParameters.setCertificateChain(entryUserB.getCertificateChain()); DSSDocument counterSignDocument = service.counterSignDocument(signedDocument, countersigningParameters, signerInfo.getSID(), new MockSignatureTokenConnection(), entryUserB); assertNotNull(counterSignDocument); counterSignDocument.save("target/countersign.p7m"); CMSSignedData data = new CMSSignedData(counterSignDocument.openStream()); SignerInformationStore informationStore = data.getSignerInfos(); Collection<SignerInformation> signers = informationStore.getSigners(); for (SignerInformation signerInformation : signers) { AttributeTable signedAttributes = signerInformation.getSignedAttributes(); Attribute attribute = signedAttributes.get(PKCSObjectIdentifiers.pkcs_9_at_contentType); assertNotNull(attribute); SignerInformationStore counterSignatures = signerInformation.getCounterSignatures(); assertNotNull(counterSignatures); Collection<SignerInformation> signersCounter = counterSignatures.getSigners(); for (SignerInformation signerCounter : signersCounter) { AttributeTable signedAttributes2 = signerCounter.getSignedAttributes(); Attribute attribute2 = signedAttributes2.get(PKCSObjectIdentifiers.pkcs_9_at_contentType); // Counter-signatures don't allow content-type assertNull(attribute2); } } SignerInformationVerifierProvider vProv = new SignerInformationVerifierProvider() { @Override public SignerInformationVerifier get(SignerId signerId) throws OperatorCreationException { if (entryUserA.getCertificate().getSerialNumber().equals(signerId.getSerialNumber())) { return new JcaSimpleSignerInfoVerifierBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME) .build(entryUserA.getCertificate().getCertificate()); } else if (entryUserB.getCertificate().getSerialNumber().equals(signerId.getSerialNumber())) { return new JcaSimpleSignerInfoVerifierBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME) .build(entryUserB.getCertificate().getCertificate()); } else { throw new IllegalStateException("no signerID matched"); } } }; // Validate both signatures by BC assertTrue(data.verifySignatures(vProv, false)); // Validate SignedDocumentValidator validator = SignedDocumentValidator.fromDocument(counterSignDocument); validator.setCertificateVerifier(new CommonCertificateVerifier()); Reports reports = validator.validateDocument(); reports.print(); DiagnosticData diagnosticData = reports.getDiagnosticData(); List<XmlDom> signatures = diagnosticData.getElements("/DiagnosticData/Signature"); assertEquals(2, signatures.size()); boolean foundCounterSignature = false; for (XmlDom xmlDom : signatures) { String type = xmlDom.getAttribute("Type"); if (AttributeValue.COUNTERSIGNATURE.equals(type)) { foundCounterSignature = true; } assertTrue(diagnosticData.isBLevelTechnicallyValid(xmlDom.getAttribute("Id"))); } assertTrue(foundCounterSignature); }
From source file:mail.SignedDataProcessor.java
License:Apache License
/** * Take a CMS SignedData message and a trust anchor and determine if * the message is signed with a valid signature from a end entity * entity certificate recognized by the trust anchor rootCert. *//*from w ww .j a v a2s . com*/ @SuppressWarnings("unchecked") public static boolean isValid(CMSSignedData signedData, X509Certificate rootCert) throws Exception { CertStore certsAndCRLs = signedData.getCertificatesAndCRLs("Collection", "BC"); SignerInformationStore signers = signedData.getSignerInfos(); Iterator it = signers.getSigners().iterator(); if (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); X509CertSelector signerConstraints = signer.getSID(); signerConstraints.setKeyUsage(getKeyUsageForSignature()); PKIXCertPathBuilderResult result = Utils.buildPath(rootCert, signer.getSID(), certsAndCRLs); return signer.verify(result.getPublicKey(), "BC"); } return false; }
From source file:net.jsign.pe.PEFile.java
License:Apache License
/** * Print detailed informations about the PE file. *//* w w w. jav a 2s.com*/ public void printInfo(PrintWriter out) { out.println("PE File"); out.println(" Name: " + raf.getName()); out.println(" Size: " + raf.length()); out.println(" Last Modified: " + new Date(raf.lastModified())); out.println(); out.println("PE Header"); out.println(" Machine: " + getMachineType()); out.println(" Number of sections: " + getNumberOfSections()); out.println(" Timestamp: " + getTimeDateStamp()); out.println(" Pointer to symbol table: 0x" + Long.toHexString(getPointerToSymbolTable())); out.println(" Number of symbols: " + getNumberOfSymbols()); out.println(" Size of optional header: " + getSizeOfOptionalHeader()); out.println(" Characteristics: 0x" + Long.toBinaryString(getCharacteristics())); out.println(); out.println("Optional Header"); PEFormat format = getFormat(); out.println( " PE Format: 0x" + Integer.toHexString(format.value) + " (" + format.label + ")"); out.println(" Linker version: " + getMajorLinkerVersion() + "." + getMinorLinkerVersion()); out.println(" Size of code: " + getSizeOfCode()); out.println(" Size of initialized data: " + getSizeOfInitializedData()); out.println(" Size of uninitialized data: " + getSizeOfUninitializedData()); out.println(" Address of entry point: 0x" + Long.toHexString(getAddressOfEntryPoint())); out.println(" Base of code: 0x" + Long.toHexString(getBaseOfCode())); if (PEFormat.PE32.equals(getFormat())) { out.println(" Base of data: 0x" + Long.toHexString(getBaseOfData())); } out.println(" Image base: 0x" + Long.toHexString(getImageBase())); out.println(" Section alignment: " + getSectionAlignment()); out.println(" File alignment: " + getFileAlignment()); out.println(" Operating system version: " + getMajorOperatingSystemVersion() + "." + getMinorOperatingSystemVersion()); out.println(" Image version: " + getMajorImageVersion() + "." + getMinorImageVersion()); out.println( " Subsystem version: " + getMajorSubsystemVersion() + "." + getMinorSubsystemVersion()); out.println(" Size of image: " + getSizeOfImage()); out.println(" Size of headers: " + getSizeOfHeaders()); out.println(" Checksum: 0x" + Long.toHexString(getCheckSum())); out.println(" Checksum (computed): 0x" + Long.toHexString(computeChecksum())); out.println(" Subsystem: " + getSubsystem()); out.println(" DLL characteristics: 0x" + Long.toBinaryString(getDllCharacteristics())); out.println(" Size of stack reserve: " + getSizeOfStackReserve()); out.println(" Size of stack commit: " + getSizeOfStackCommit()); out.println(" Size of heap reserve: " + getSizeOfHeapReserve()); out.println(" Size of heap commit: " + getSizeOfHeapCommit()); out.println(" Number of RVA and sizes: " + getNumberOfRvaAndSizes()); out.println(); out.println("Data Directory"); for (DataDirectoryType type : DataDirectoryType.values()) { DataDirectory entry = getDataDirectory(type); if (entry != null && entry.getVirtualAddress() != 0) { out.printf(" %-30s 0x%08x %8d bytes\n", type, entry.getVirtualAddress(), entry.getSize()); } } out.println(); int sectionTableOffset = getDataDirectoryOffset() + 8 * getNumberOfRvaAndSizes(); out.println("Sections"); out.println(" Name Virtual Size Virtual Address Raw Data Size Raw Data Ptr Characteristics"); for (int i = 0; i < getNumberOfSections(); i++) { Section section = new Section(this, sectionTableOffset + 40 * i); out.printf(" #%d %-8s %8d 0x%08x %8d 0x%08x %s\n", i + 1, section.getName(), section.getVirtualSize(), section.getVirtualAddress(), section.getSizeOfRawData(), section.getPointerToRawData(), section.getCharacteristics()); } out.println(); List<CMSSignedData> signatures = getSignatures(); if (!signatures.isEmpty()) { out.println("Signatures"); for (CMSSignedData signedData : signatures) { SignerInformation signerInformation = signedData.getSignerInfos().getSigners().iterator().next(); X509CertificateHolder certificate = (X509CertificateHolder) signedData.getCertificates() .getMatches(signerInformation.getSID()).iterator().next(); String commonName = certificate.getSubject().getRDNs(X509ObjectIdentifiers.commonName)[0].getFirst() .getValue().toString(); AttributeTable unsignedAttributes = signerInformation.getUnsignedAttributes(); boolean timestamped = unsignedAttributes != null && (unsignedAttributes.get(PKCSObjectIdentifiers.pkcs_9_at_counterSignature) != null || unsignedAttributes.get(AuthenticodeObjectIdentifiers.SPC_RFC3161_OBJID) != null); DigestAlgorithm algorithm = DigestAlgorithm .of(signerInformation.getDigestAlgorithmID().getAlgorithm()); out.println(" " + commonName + " " + (algorithm != null ? "[" + algorithm.id + "] " : "") + (timestamped ? "(timestamped)" : "")); } } }
From source file:net.jsign.SignatureAssert.java
License:Apache License
public static void assertTimestamped(String message, CMSSignedData signedData) { SignerInformation signerInformation = signedData.getSignerInfos().getSigners().iterator().next(); AttributeTable unsignedAttributes = signerInformation.getUnsignedAttributes(); Assert.assertNotNull(message + " (missing unauthenticated attributse)", unsignedAttributes); Attribute authenticodeTimestampAttribute = unsignedAttributes.get(CMSAttributes.counterSignature); Attribute rfc3161TimestampAttribute = unsignedAttributes .get(AuthenticodeObjectIdentifiers.SPC_RFC3161_OBJID); Assert.assertTrue(message + " (no counter signature attribute found)", authenticodeTimestampAttribute != null || rfc3161TimestampAttribute != null); if (authenticodeTimestampAttribute != null) { Assert.assertNotNull(message + " (counter signature attribute value is null)", authenticodeTimestampAttribute.getAttributeValues()); Assert.assertTrue(message + " (counter signature attribute value is empty)", authenticodeTimestampAttribute.getAttributeValues().length > 0); } else {/*from w w w . ja v a2 s . c o m*/ Assert.assertNotNull(message + " (counter signature attribute value is null)", rfc3161TimestampAttribute.getAttributeValues()); Assert.assertTrue(message + " (counter signature attribute value is empty)", rfc3161TimestampAttribute.getAttributeValues().length > 0); } }
From source file:net.jsign.timestamp.AuthenticodeTimestamper.java
License:Apache License
@Override protected AttributeTable getUnsignedAttributes(CMSSignedData token) { SignerInformation timestampSignerInformation = token.getSignerInfos().getSigners().iterator().next(); Attribute counterSignature = new Attribute(CMSAttributes.counterSignature, new DERSet(timestampSignerInformation.toASN1Structure())); return new AttributeTable(counterSignature); }
From source file:net.jsign.timestamp.Timestamper.java
License:Apache License
/** * Return the encrypted digest of the specified signature. *//*from w w w. j a v a 2 s . c o m*/ private byte[] getEncryptedDigest(CMSSignedData sigData) { SignerInformation signerInformation = sigData.getSignerInfos().getSigners().iterator().next(); return signerInformation.toASN1Structure().getEncryptedDigest().getOctets(); }