List of usage examples for org.bouncycastle.cms CMSSignedData getSignedContent
public CMSTypedData getSignedContent()
From source file:it.doqui.index.ecmengine.business.personalization.splitting.index.lucene.P7mHandler.java
License:Open Source License
public static byte[] sbusta(byte[] p7m_bytes) { byte[] byte_out = null; CMSSignedData cms = null; ByteArrayOutputStream out = null; try {//from w w w . j a v a 2 s . com cms = new CMSSignedData(p7m_bytes); CMSProcessable cmsp = cms.getSignedContent(); if (cmsp != null) { out = new ByteArrayOutputStream(); cmsp.write(out); byte_out = out.toByteArray(); out.close(); } } catch (Exception e) { byte_out = null; } finally { try { out.close(); } catch (Exception e) { } } return byte_out; }
From source file:it.govpay.core.utils.SignUtils.java
License:Open Source License
public static byte[] cleanCadesSignedFile(byte[] rt) throws KeyStoreException, CMSException, IOException { CMSSignedData cms = new CMSSignedData(rt); return ((byte[]) cms.getSignedContent().getContent()); }
From source file:it.trento.comune.j4sign.cms.utils.CMSBuilder.java
License:Open Source License
/** * Merges two SignedData Objects/*ww w . j a va2 s . co m*/ * * @param cms * existing cms signed data * @param s * new cms signed data * @param checkSameDigest * check if messageDigest value is the same for all signers? * @return the merged cms */ public CMSSignedData mergeCms(CMSSignedData cms, CMSSignedData s) { try { SignerInformationStore existingSignersStore = cms.getSignerInfos(); Collection<SignerInformation> existingSignersCollection = existingSignersStore.getSigners(); SignerInformationStore newSignersStore = s.getSignerInfos(); Collection<SignerInformation> newSignersCollection = newSignersStore.getSigners(); // do some sanity checks if (existingSignersCollection.isEmpty()) { System.out.println("Error: existing signed data has no signers."); return null; } if (newSignersCollection.isEmpty()) { System.out.println("Error: new signed data has no signers."); return null; } byte[] cmsBytes = (byte[]) cms.getSignedContent().getContent(); byte[] sBytes = (byte[]) s.getSignedContent().getContent(); if (!Arrays.equals(cmsBytes, sBytes)) { System.out.println("Error: content data differs."); return null; } /* Digest could differ, if hashing algorithms are different if (checkSameDigest) if (!isSameDigest(existingSignersCollection, newSignersCollection)) { System.out .println("Error: messageDigest for some signers differ."); return null; } */ CertStore existingCertsStore = cms.getCertificatesAndCRLs("Collection", "BC"); CertStore newCertsStore = s.getCertificatesAndCRLs("Collection", "BC"); X509Store x509Store = cms.getAttributeCertificates("Collection", "BC"); X509Store newX509Store = s.getAttributeCertificates("Collection", "BC"); Collection newCertsCollection = newCertsStore.getCertificates(null); Iterator<SignerInformation> existingSignersIterator = existingSignersCollection.iterator(); // ciclo tra tutti i vecchi firmatari while (existingSignersIterator.hasNext()) { SignerInformation exSigner = existingSignersIterator.next(); // Controllo la presenza di certificati firmatario corrente // tra i nuovi certificati Collection exSignerCerts = newCertsStore.getCertificates(exSigner.getSID()); // ... e nel caso li rimuovo Iterator exSignerCertsIt = exSignerCerts.iterator(); while (exSignerCertsIt.hasNext()) newCertsCollection.remove(exSignerCertsIt.next()); } // Rigenero la lista dei nuovi certificati, // ora disgiunta da quella dei vecchi newCertsStore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(newCertsCollection), "BC"); // Si crea un CMSSignedDataGenerator locale, // inizializzandolo conn i dati gi presenti. CMSSignedDataGenerator signGen = new CMSSignedDataGenerator(); // add old certs signGen.addCertificatesAndCRLs(existingCertsStore); // add old certs attributes signGen.addAttributeCertificates(x509Store); // add old signers signGen.addSigners(existingSignersStore); // add new certs signGen.addCertificatesAndCRLs(newCertsStore); // add new certs attributes signGen.addAttributeCertificates(newX509Store); // add new signers signGen.addSigners(newSignersStore); CMSProcessable cp = new CMSProcessableByteArray((byte[]) cms.getSignedContent().getContent()); s = signGen.generate(cp, true, "BC"); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchProviderException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CMSException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CertStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidAlgorithmParameterException e) { // TODO Auto-generated catch block e.printStackTrace(); } return s; }
From source file:it.trento.comune.j4sign.verification.RootsVerifier.java
License:Open Source License
private InputStream getCmsInputStream(String path) { FileInputStream is = null;/*w w w. j a v a 2 s . c om*/ try { is = new FileInputStream(path); } catch (FileNotFoundException ex) { log.severe("Errore nell'acquisizione del file: " + ex); } ByteArrayInputStream bais = null; try { CMSSignedData cms = new CMSSignedData(is); ByteArrayOutputStream baos = new ByteArrayOutputStream(); cms.getSignedContent().write(baos); bais = new ByteArrayInputStream(baos.toByteArray()); } catch (CMSException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return bais; }
From source file:it.treviso.provincia.freesigner.applet.FreeSignerSignApplet3.java
License:Open Source License
/** * Prepares a signing procedure./* w w w .java 2 s . c o m*/ * * @param digestAlg * String * @param encryptionAlg * String * @param digestOnToken * boolean * @throws InvalidKeyException * @throws CertificateEncodingException * @throws SignatureException * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws IOException * @throws CMSException */ private void openSignature(String digestAlg, String encryptionAlg, boolean digestOnToken) throws InvalidKeyException, CertificateEncodingException, SignatureException, NoSuchProviderException, NoSuchAlgorithmException, IOException, CMSException { File inputFile = new File(fileDaAprire); if (fileDaAprire.substring(fileDaAprire.lastIndexOf('.') + 1, fileDaAprire.length()).toLowerCase() .equalsIgnoreCase("p7m")) { log.println("Resigning in progress..."); // do resigning things resign = true; byte[] bytesFromFile = getBytesFromFile(inputFile); byte[] certData; try { certData = Base64.decode(bytesFromFile); } catch (Exception eb64) { certData = bytesFromFile; } CMSSignedData actualFile = new CMSSignedData(certData); this.msg = new CMSProcessableByteArray((byte[]) actualFile.getSignedContent().getContent()); } else { this.msg = new CMSProcessableByteArray(getBytesFromFile(inputFile)); } /** * Code notes: * * On CLITest.java there is a method called getSignerInfoGenerator that gives some infos about the generator that then is added on the * * ExternalSignatureCMSSignedDataGenerator() with cmsGenerator.addSignerInf(sig) * */ this.cmsGenerator = new ExternalSignatureCMSSignedDataGenerator(); this.signersCertList = new ArrayList(); log.println("\nCalculating digest ...\n"); this.signerInfoGenerator = new ExternalSignatureSignerInfoGenerator(digestAlg, encryptionAlg); /* Cades Impl. */ this.signerInfoGenerator.setCertificate(certforcades); /* End Cades Impl. */ byte[] rawDigest = null; byte[] dInfoBytes = null; byte[] paddedBytes = null; /** * notes for multiple signing: * this.msg should be a CMSProcessableByteArray of the signedContent. * bytesToSign should be extracted with (byte[]) CMSSignedData.getSignedContent().getContent() */ byte[] bytesToSign = this.signerInfoGenerator.getBytesToSign(PKCSObjectIdentifiers.data, msg, "BC"); /* * Let's calculate DigestInfo in any case (even if digestOnToken is * TRUE) , in order to compare with decryption result */ rawDigest = applyDigest(digestAlg, bytesToSign); log.println("Raw digest bytes:\n" + formatAsHexString(rawDigest)); log.println("Encapsulating in a DigestInfo..."); dInfoBytes = encapsulateInDigestInfo(digestAlg, rawDigest); log.println("DigestInfo bytes:\n" + formatAsHexString(dInfoBytes)); if (!digestOnToken) { // MessageDigest md = MessageDigest.getInstance(digestAlg); // md.update(bytesToSign); // byte[] digest = md.digest(); // // log.println("digestAlg digest:\n" + formatAsHexString(digest)); // log.println("Done."); setEncodedDigest(encodeFromBytes(dInfoBytes)); } }
From source file:it.treviso.provincia.freesigner.crl.CertificationAuthorities.java
License:Open Source License
private static InputStream getCmsInputStream(URL url) { ByteArrayInputStream bais = null; try {//from w w w .j a va2 s . c o m CMSSignedData cms = new CMSSignedData(url.openStream()); cms.getSignedContent(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); cms.getSignedContent().write(baos); bais = new ByteArrayInputStream(baos.toByteArray()); } catch (CMSException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return bais; }
From source file:net.jsign.timestamp.Timestamper.java
License:Apache License
protected CMSSignedData modifySignedData(CMSSignedData sigData, AttributeTable unsignedAttributes, Collection<X509CertificateHolder> extraCertificates) throws IOException, CMSException { SignerInformation signerInformation = sigData.getSignerInfos().getSigners().iterator().next(); signerInformation = SignerInformation.replaceUnsignedAttributes(signerInformation, unsignedAttributes); Collection<X509CertificateHolder> certificates = new ArrayList<X509CertificateHolder>(); certificates.addAll(sigData.getCertificates().getMatches(null)); if (extraCertificates != null) { certificates.addAll(extraCertificates); }/* w w w. j av a 2 s . c o m*/ Store<X509CertificateHolder> certificateStore = new CollectionStore<X509CertificateHolder>(certificates); AuthenticodeSignedDataGenerator generator = new AuthenticodeSignedDataGenerator(); generator.addCertificates(certificateStore); generator.addSigners(new SignerInformationStore(signerInformation)); ASN1ObjectIdentifier contentType = new ASN1ObjectIdentifier(sigData.getSignedContentTypeOID()); ASN1Encodable content = ASN1Sequence.getInstance(sigData.getSignedContent().getContent()); return generator.generate(contentType, content); }
From source file:net.sf.assinafacil.AssinadorMSCAPI.java
License:Open Source License
@Override /***//from w w w.j a va 2 s . com * 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.AssinaFacilApp.java
License:Open Source License
public byte[] getSignedContent(File fileInput) throws GeneralSecurityException, IOException { CMSSignedData signedData = null; CMSProcessable content = null;/* w ww. j a v a2 s .c o m*/ 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."); } }
From source file:net.sf.assinafacil.AssinaFacilApp.java
License:Open Source License
public boolean extractSignedContent(File fileInput, File fileOutput) throws GeneralSecurityException, IOException { CMSSignedData signedData = null; CMSProcessable content = null;//from ww w . j a v a2 s . c o m FileOutputStream fos = new FileOutputStream(fileOutput); try { signedData = new CMSSignedData(new FileInputStream(fileInput)); content = signedData.getSignedContent(); content.write(fos); fos.close(); return true; } catch (CMSException e) { throw new GeneralSecurityException("Arquivo no assinado ou formatao invlida."); } }