List of usage examples for org.bouncycastle.cms CMSSignedData CMSSignedData
public CMSSignedData(ContentInfo sigData) throws CMSException
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 www . jav a 2 s.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 ww .ja v a 2 s. com * 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 ww .ja v a 2s .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:module.signature.util.XAdESValidator.java
License:Open Source License
/** * @author joao.antunes@tagus.ist.utl.pt adapted it from {@link #validateXMLSignature(String)} * @param streamWithSignature//from w w w .j av a2 s . c om * the {@link InputStream} that has the signature content * @return true if it's valid, false otherwise */ public boolean validateXMLSignature(InputStream streamWithSignature) { try { // get the xsd schema Validator validator = schemaXSD.newValidator(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder parser = dbf.newDocumentBuilder(); ErrorHandler eh = new ErrorHandler() { @Override public void warning(SAXParseException exception) throws SAXException { throw new UnsupportedOperationException("Not supported yet.", exception); } @Override public void error(SAXParseException exception) throws SAXException { throw new UnsupportedOperationException("Not supported yet.", exception); } @Override public void fatalError(SAXParseException exception) throws SAXException { throw new UnsupportedOperationException("Not supported yet.", exception); } }; // parse the document parser.setErrorHandler(eh); Document document = parser.parse(streamWithSignature); // XAdES extension NodeList nlObject = document.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Object"); // XMLDSIG NodeList nlSignature = document.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Signature"); if (checkSchema) { if (nlObject.getLength() < 1) { return false; } if (nlSignature.getLength() < 1) { return false; } // parse the XML DOM tree againts the XSD schema validator.validate(new DOMSource(nlSignature.item(0))); } if (checkSignature) { // Validate Every Signature Element (including CounterSignatures) for (int i = 0; i < nlSignature.getLength(); i++) { Element signature = (Element) nlSignature.item(i); // String baseURI = fileToValidate.toURL().toString(); XMLSignature xmlSig = new XMLSignature(signature, null); KeyInfo ki = xmlSig.getKeyInfo(); // If signature contains X509Data if (ki.containsX509Data()) { NodeList nlSigningTime = signature.getElementsByTagNameNS(xadesNS, "SigningTime"); Date signingDate = null; if (nlSigningTime.item(0) != null) { StringBuilder xmlDate = new StringBuilder(nlSigningTime.item(0).getTextContent()) .deleteCharAt(22); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); signingDate = simpleDateFormat.parse(xmlDate.toString()); } //verificao OCSP //TODO FENIX-189 joantune: na realidade acho que isto no verifica mesmo a revocao.. a no ser que a keystore indicada seja actualizada regularmente. if (checkRevocation) { //keystore certs cc, raiz estado Security.setProperty("ocsp.enable", "true"); //System.setProperty("com.sun.security.enableCRLDP", "true"); CertificateFactory cf = CertificateFactory.getInstance("X.509"); CertPath certPath = cf .generateCertPath(Collections.singletonList(ki.getX509Certificate())); // TrustAnchor trustA = new TrustAnchor(ki.getX509Certificate(), null); // Set trustAnchors = Collections.singleton(trustA); PKIXParameters params = new PKIXParameters(cartaoCidadaoKeyStore); params.setRevocationEnabled(true); // validar o estado na data da assinatura if (nlSigningTime.item(0) != null) { params.setDate(signingDate); } try { CertPathValidator cpValidator = CertPathValidator.getInstance("PKIX"); CertPathValidatorResult result = cpValidator.validate(certPath, params); //TODO FENIX-196 probably one would want to send a notification here } catch (CertPathValidatorException ex) { return false; } catch (InvalidAlgorithmParameterException ex) { return false; } } // verifica a validade do certificado no momento da assinatura if (checkValidity) { if (nlSigningTime.item(0) != null) { // continue if there is no SigningTime, if CounterSignature isn't XAdES try { ki.getX509Certificate().checkValidity(signingDate); } catch (CertificateExpiredException ex) { return false; } catch (CertificateNotYetValidException ex) { return false; } } } // validate against Certificate Public Key boolean validSignature = xmlSig.checkSignatureValue(ki.getX509Certificate().getPublicKey()); if (!validSignature) { return false; } } // if signature includes KeyInfo KeyValue, also check against it if (ki.containsKeyValue()) { boolean validSignature = xmlSig.checkSignatureValue(ki.getPublicKey()); if (!validSignature) { return false; } } //let's check the SignatureTimeStamp(s) joantune NodeList signatureTimeStamps = signature.getElementsByTagNameNS("*", "SignatureTimeStamp"); Element signatureValue = null; if (signatureTimeStamps.getLength() > 0) { signatureValue = (Element) signature.getElementsByTagNameNS("*", "SignatureValue").item(0); } for (int j = 0; j < signatureTimeStamps.getLength(); j++) { logger.debug("Found a SignatureTimeStamp"); Element signatureTimeStamp = (Element) signatureTimeStamps.item(j); //for now we are ignoring the XMLTimeStamp element, let's iterate through all of the EncapsulatedTimeStamp that we find NodeList encapsulatedTimeStamps = signatureTimeStamp.getElementsByTagNameNS("*", "EncapsulatedTimeStamp"); for (int k = 0; k < encapsulatedTimeStamps.getLength(); k++) { logger.debug("Found an EncapsulatedTimeStamp"); Element encapsulatedTimeStamp = (Element) encapsulatedTimeStamps.item(k); //let's check it // note, we have the timestamptoken, not the whole response, that is, we don't have the status field ASN1Sequence signedTimeStampToken = ASN1Sequence .getInstance(Base64.decode(encapsulatedTimeStamp.getTextContent())); CMSSignedData cmsSignedData = new CMSSignedData( Base64.decode(encapsulatedTimeStamp.getTextContent())); TimeStampToken timeStampToken = new TimeStampToken(cmsSignedData); //let's construct the Request to make sure this is a valid response //let's generate the digest MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); byte[] digest = sha1.digest(signatureValue.getTextContent().getBytes("UTF-8")); //let's make sure the digests are the same if (!Arrays.equals(digest, timeStampToken.getTimeStampInfo().getMessageImprintDigest())) { //TODO probably want to send an e-mail if this happens, as it's clearly a sign of tampering //FENIX-196 logger.debug("Found a different digest in the timestamp!"); return false; } try { //TODO for now we won't use the provided certificates that came with the TST // X509Store certificateStore = (X509Store) timeStampToken.getCertificates(); // JcaDigestCalculatorProviderBuilder builder = new JcaDigestCalculatorProviderBuilder(); // timeStampToken.validate(tsaCert, "BC"); // timeStampToken.validate(new SignerInformationVerifier(new JcaContentVerifierProviderBuilder() // .build(tsaCert), builder.build())); timeStampToken.validate(new SignerInformationVerifier( new JcaContentVerifierProviderBuilder().build(tsaCert), new BcDigestCalculatorProvider())); //let's just verify that the timestamp was done in the past :) - let's give a tolerance of 5 mins :) Date currentDatePlus5Minutes = new Date(); //let's make it go 5 minutes ahead currentDatePlus5Minutes.setMinutes(currentDatePlus5Minutes.getMinutes() + 5); if (!timeStampToken.getTimeStampInfo().getGenTime() .before(currentDatePlus5Minutes)) { //FENIX-196 probably we want to log this! //what the heck, timestamp is done in the future!! (clocks might be out of sync) logger.warn("Found a timestamp in the future!"); return false; } logger.debug("Found a valid TimeStamp!"); //as we have no other timestamp elements in this signature, this means all is ok! :) //(point 5) of g.2.2.16.1.3 on the specs } catch (TSPException exception) { logger.debug("TimeStamp response did not validate", exception); return false; } } } } } } catch (IOException ex) { Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (ParserConfigurationException ex) { Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (SAXException ex) { Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (Exception ex) { Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex); return false; } return true; }
From source file:net.jsign.timestamp.AuthenticodeTimestamper.java
License:Apache License
protected CMSSignedData timestamp(DigestAlgorithm algo, byte[] encryptedDigest) throws IOException, TimestampingException { AuthenticodeTimeStampRequest timestampRequest = new AuthenticodeTimeStampRequest(encryptedDigest); byte[] request = Base64.encode(timestampRequest.getEncoded("DER")); HttpURLConnection conn = (HttpURLConnection) tsaurl.openConnection(); conn.setConnectTimeout(10000);//from w w w. j a v a 2 s. c o m conn.setReadTimeout(10000); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-type", "application/octet-stream"); conn.setRequestProperty("Content-length", String.valueOf(request.length)); conn.setRequestProperty("Accept", "application/octet-stream"); conn.setRequestProperty("User-Agent", "Transport"); conn.getOutputStream().write(request); conn.getOutputStream().flush(); if (conn.getResponseCode() >= 400) { throw new IOException("Unable to complete the timestamping due to HTTP error: " + conn.getResponseCode() + " - " + conn.getResponseMessage()); } try { byte[] response = Base64.decode(toBytes(conn.getInputStream())); return new CMSSignedData(response); } catch (Exception e) { throw new TimestampingException("Unable to complete the timestamping", e); } }
From source file:net.ripe.rpki.commons.provisioning.cms.ProvisioningCmsObject.java
License:BSD License
/** * This is used to check against replay attacks, see <a * href="http://tools.ietf.org/html/draft-ietf-sidr-rescerts-provisioning-09#section-3.1.2" * >http://tools.ietf.org/html/draft-ietf-sidr-rescerts-provisioning-09#section-3.1.2</a><br > */// w ww . j a v a 2s. c o m public DateTime getSigningTime() { try { CMSSignedData cmsSignedData = new CMSSignedData(encodedContent); SignerInformationStore sis = cmsSignedData.getSignerInfos(); @SuppressWarnings("unchecked") Collection<SignerInformation> signers = sis.getSigners(); for (SignerInformation signerInformation : signers) { AttributeTable signedAttributes = signerInformation.getSignedAttributes(); Attribute signingTime = signedAttributes.get(CMSAttributes.signingTime); @SuppressWarnings("unchecked") Enumeration<Object> en = signingTime.getAttrValues().getObjects(); while (en.hasMoreElements()) { Object obj = en.nextElement(); if (obj instanceof DERUTCTime) { DERUTCTime derTime = (DERUTCTime) obj; return new DateTime(derTime.getDate()); } } } throw new IllegalArgumentException("Malformed encoded cms content"); } catch (CMSException e) { throw new IllegalArgumentException("Malformed encoded cms content", e); } catch (ParseException e) { throw new IllegalArgumentException("Malformed encoded cms content", e); } }
From source file:net.sf.assinafacil.AssinadorMSCAPI.java
License:Open Source License
@Override /***//from w w w . ja va2 s . c o m * Assina digitalmente o arquivo de entrada e gera o arquivo de sa\u00edda. * nesse caso a senha n\u00e3o \u00e9 utilizada pois o keystore \u00e9 um token suja senha * ser\u00e1 requerida pelo MSCAPI. * * @return Mensagem de status que ser\u00e1 exibida na interface. */ public String signFile(String fileInput, String signedFileName, String password, String certificateAlias) throws Exception { if (!isInitialized()) { throw new java.security.KeyException( "Chaveiro n\u00c3\u00a3o inicializado ou erro ao acess\u00c3\u00a1-lo."); } PrivateKey priv = null; Certificate storecert = null; Certificate[] certChain = null; ArrayList<Certificate> certList = new ArrayList<Certificate>(); CertStore certs = null; CMSSignedData signedData = null; CMSProcessable content = null; byte[] signeddata = null; String retorno; if (signedFileName == null) signedFileName = fileInput; certChain = keyStore.getCertificateChain(certificateAlias); if (certChain == null) { throw new GeneralSecurityException( "Cadeia do certificado " + certificateAlias + " n\u00c3\u00a3o encontrada."); } certList.addAll(Arrays.asList(certChain)); certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList)); storecert = keyStore.getCertificate(certificateAlias); priv = (PrivateKey) (keyStore.getKey(certificateAlias, null)); if (priv == null) { throw new java.security.AccessControlException( "Acesso \u00c3\u00a0 chave foi negado... senha inv\u00c3\u00a1lida?"); } CMSSignedDataGenerator signGen = new CMSSignedDataGenerator(); signGen.addSigner(priv, (X509Certificate) storecert, CMSSignedDataGenerator.DIGEST_SHA1); signGen.addCertificatesAndCRLs(certs); try { signedData = new CMSSignedData(new FileInputStream(fileInput)); content = signedData.getSignedContent(); signGen.addSigners(signedData.getSignerInfos()); signGen.addCertificatesAndCRLs(signedData.getCertificatesAndCRLs("Collection", "BC")); CMSSignedData signedData2 = signGen.generate(content, true, PROVIDER_STRING); signeddata = signedData2.getEncoded(); retorno = "Arquivo " + signedFileName + " foi assinado novamente."; } catch (CMSException e) { content = new CMSProcessableFile(new File(fileInput)); signedData = signGen.generate(content, true, PROVIDER_STRING); signeddata = signedData.getEncoded(); retorno = "Arquivo " + signedFileName + " foi assinado."; } FileOutputStream fileOutput = new FileOutputStream(signedFileName); fileOutput.write(signeddata); fileOutput.close(); Logger.getLogger(AssinadorMSCAPI.class.getName()).log(Level.INFO, retorno); return retorno; }
From source file:net.sf.assinafacil.AssinadorMSCAPI.java
License:Open Source License
/*** * Verifica se o arquivo j\u00e1 foi assinado... feio pois identifica via exception... * mas \u00e9 r\u00e1pido e sei que desenvolvedores mais cuidadosos me ajudar\u00e3o a melhorar * inclusive esse trecho do c\u00f3digo. */// ww w . j av a2s . com public boolean isSignedFile(String fileName) { CMSSignedData signedData = null; try { signedData = new CMSSignedData(new FileInputStream(fileName)); return signedData.getContentInfo().getContentType() .equals(org.bouncycastle.asn1.cms.CMSObjectIdentifiers.signedData); } catch (FileNotFoundException ex) { Logger.getLogger(AssinadorMSCAPI.class.getName()).log(Level.INFO, "Arquivo " + fileName + " n\u00e3o encontrado", ex); return false; } catch (CMSException ex) { // Malformed content. // DEBUG? Logger.getLogger(AssinadorMSCAPI.class.getName()).log(Level.SEVERE, null, ex); return false; } }
From source file:net.sf.assinafacil.AssinaFacilApp.java
License:Open Source License
public CertStore getCertificates(File fileInput) throws java.security.SignatureException, FileNotFoundException { CMSSignedData signedData = null;//from ww w . java2 s. c om CertStore certs = null; try { signedData = new CMSSignedData(new FileInputStream(fileInput)); certs = signedData.getCertificatesAndCRLs("Collection", "BC"); return certs; } catch (NoSuchAlgorithmException ex) { Logger.getLogger(AssinadorMSCAPI.class.getName()).log(Level.SEVERE, null, ex); return null; } catch (NoSuchProviderException ex) { Logger.getLogger(AssinadorMSCAPI.class.getName()).log(Level.SEVERE, null, ex); return null; } catch (CMSException e) { throw new SignatureException("Arquivo no assinado ou formato invlido"); } }
From source file:net.sf.assinafacil.AssinaFacilApp.java
License:Open Source License
public byte[] getSignedContent(File fileInput) throws GeneralSecurityException, IOException { CMSSignedData signedData = null;//from ww w. j a v a 2 s. c om CMSProcessable content = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { signedData = new CMSSignedData(new FileInputStream(fileInput)); content = signedData.getSignedContent(); content.write(baos); return baos.toByteArray(); } catch (CMSException e) { throw new GeneralSecurityException("Arquivo no assinado ou formatao invlida."); } }