List of usage examples for org.bouncycastle.cms CMSSignedData getEncoded
public byte[] getEncoded() throws IOException
From source file:it.trento.comune.j4sign.examples.CLITest.java
License:Open Source License
/** * Tests (possibly multiple) digital signatures using PKCS#11 tokens. After * correct integrity verification of all signatures, the CMS signed message * is saved on the filesystem under the users's home directory. * // w w w . j a va 2s . co m */ public void testExternalSignature() { try { System.out.println("\n========= CMS (PKCS7) Signed message test ========\n"); System.out.print("The test message to sign is:\t"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write(this.msgBytes); System.out.println(baos.toString()); System.out.print("As exadecimal string:\t\t"); System.out.println(formatAsString(this.msgBytes, " ", WRAP_AFTER)); System.out.println(); CMSProcessable msg = new CMSProcessableByteArray(this.msgBytes); // questa versione del generatore priva della classe interna // per // la generazione delle SignerInfo, che stata promossa a // classe a // s. ExternalSignatureCMSSignedDataGenerator gen = new ExternalSignatureCMSSignedDataGenerator(); // Conterr la lista dei certificati; come minimo dovr // contenere i certificati dei firmatari; opzionale, ma // consigliabile, // l'aggiunta dei certificati root per completare le catene di // certificazione. ArrayList certList = new ArrayList(); ExternalSignatureSignerInfoGenerator sig = null; String answer = "STARTVALUE"; String question = "Do you want to sign this message?"; String defaultChoice = null; int i = 0; Prompt prompt = new Prompt(); String[] choices = { "Y", "N" }; while (!answer.equals("N")) { answer = prompt.question(question, "Type Y or N:", choices, defaultChoice); if (answer.equals("Y")) { System.out.println("========================"); System.out.println("ADDING SIGNATURE " + i); if (detectCardAndCriptoki()) { System.out.println("Starting signing process."); // System.out // .println("Applying SHA1 digest with RSA // encryption."); sig = getSignerInfoGenerator(msg, this.digestAlg, this.encAlg, this.makeDigestOnToken, // digest // on // token? certList); if (sig != null) gen.addSignerInf(sig); } // if card detected question = "\nAdd another signature?"; defaultChoice = "N"; answer = "STARTVALUE"; } i++; } if (certList.size() != 0) { // Per passare i certificati al generatore li si incapsula // in un // CertStore. CertStore store = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); System.out.println("Adding certificates ... "); gen.addCertificatesAndCRLs(store); // Finalmente, si pu creare il l'oggetto CMS. System.out.println("Generating CMSSignedData "); CMSSignedData s = gen.generate(msg, true); // Verifica System.out.println("\nStarting CMSSignedData verification ... "); // recupero dal CMS la lista dei certificati Store certs = s.getCertificates(); // Recupero i firmatari. SignerInformationStore signers = s.getSignerInfos(); Collection<?> c = signers.getSigners(); System.out.println(c.size() + " signers found."); Iterator it = c.iterator(); // ciclo tra tutti i firmatari i = 0; while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); Collection<?> certCollection = certs.getMatches(signer.getSID()); if (certCollection.size() == 1) { // Iterator certIt = certCollection.iterator(); // X509Certificate cert = (X509Certificate) // certIt.next(); X509CertificateHolder ch = (X509CertificateHolder) certCollection.toArray()[0]; X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC") .getCertificate(ch); 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("====================================" * ); */ if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert))) { System.out.println("SIGNATURE " + i + " OK!"); } else System.err.println("SIGNATURE " + i + " Failure!"); } else System.out.println("There is not exactly one certificate for this signer!"); i++; } // writing CMS file to user's home directory this.filePath = System.getProperty("user.home") + System.getProperty("file.separator") + "ciao.txt.p7m"; System.out.println("\nSAVING FILE TO: " + filePath); FileOutputStream fos = new FileOutputStream(filePath); fos.write(s.getEncoded()); fos.flush(); fos.close(); } } catch (Exception ex) { System.err.println("EXCEPTION:\n" + ex); } }
From source file:it.trento.comune.j4sign.examples.CMSServlet.java
License:Open Source License
/** * Saves a CMS signed data file on the server file system; the extension * should be ".p7m" according to italian rules. * /*from w ww .jav a 2 s . c o m*/ * @param s * the {@link CMSSignedData} object to save. * @param filePath * full path of the file. * @return true if the file was correctly saved, false otherwise. */ private boolean saveFile(CMSSignedData s, String filePath) { try { System.out.println("\nSAVING FILE TO: " + filePath); FileOutputStream fos = new FileOutputStream(filePath); fos.write(s.getEncoded()); fos.flush(); fos.close(); return true; } catch (IOException e3) { System.out.println("IO Error: " + e3); return false; } }
From source file:it.trento.comune.j4sign.examples.GUITest.java
License:Open Source License
/** * The "control center" of the class, mandatory to satisfy the * java.awt.event.ActionListener interface contract. * /*w w w.ja va 2s . c o m*/ * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(java.awt.event.ActionEvent e) { try { // sign action if (e.getSource() == pwd) { if ("".equals(dataArea.getText())) return; // disable text area modification. this.f.setEnabled(false); this.dataArea.setEditable(false); if (detectCardAndCriptoki()) { openSignature(CMSSignedDataGenerator.DIGEST_SHA256, CMSSignedDataGenerator.ENCRYPTION_RSA, this.makeDigestOnToken); // this launches the signing thread (see task above) sign(); } // end of if( detect... } if (e.getSource() == f) { log.println("Loading file..."); String filePath = System.getProperty("user.home") + System.getProperty("file.separator"); JFileChooser fc = new JFileChooser(new File(filePath)); // Show dialog; this method does not return until dialog is // closed if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { // Get the selected file File file = fc.getSelectedFile(); String typeDesc = fc.getTypeDescription(file); try { if (isTextFile(file)) { FileInputStream fis = new FileInputStream(file); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int bytesRead = -1; while ((bytesRead = fis.read(buffer, 0, buffer.length)) >= 0) { baos.write(buffer, 0, bytesRead); } fis.close(); log.println("File: '" + file.getAbsolutePath() + "' loaded."); dataArea.setText(baos.toString()); this.setFileToSign(file); if (!"".equals(dataArea.getText()) && getCertificate() != null) pwd.setEnabled(true); else pwd.setEnabled(false); } else { JOptionPane.showMessageDialog(null, "This does not appears as a text file!", "Error loading file.", JOptionPane.ERROR_MESSAGE); log.println("This does not appears as a text file!"); } } catch (IOException ioe) { System.err.println(ioe); } } } if (e.getSource() == c) { log.println("Saving signer certificate"); String filePath = System.getProperty("user.home") + System.getProperty("file.separator"); JFileChooser fc = new JFileChooser(new File(filePath)); // Show dialog; this method does not return until dialog is // closed fc.showSaveDialog(this); // Get the selected file File file = fc.getSelectedFile(); FileOutputStream fos = new FileOutputStream(file); fos.write(getCertificate()); fos.flush(); fos.close(); log.println("Signer certificate saved to: " + file.getAbsolutePath()); } if (e.getSource() == s) { log.println("Building CMSSignedData..."); CMSSignedData cms = buildCMSSignedData(); log.println("Saving signed message"); String dirPath = System.getProperty("user.home"); if (this.getFileToSign() != null) { dirPath = this.getFileToSign().getParent(); } dirPath = dirPath + System.getProperty("file.separator"); JFileChooser fc = new JFileChooser(new File(dirPath)); String p7mFilePath = (this.getFileToSign() != null) ? this.getFileToSign().getAbsolutePath() + ".p7m" : dirPath + "guitest.txt.p7m"; fc.setSelectedFile(new File(p7mFilePath)); // Show dialog; this method does not return until dialog is // closed fc.showSaveDialog(this); // Get the selected file File file = fc.getSelectedFile(); FileOutputStream fos = new FileOutputStream(file); fos.write(cms.getEncoded()); fos.flush(); fos.close(); log.println("Signed message saved to: " + file.getAbsolutePath()); } } catch (Exception ex) { log.println(ex.toString()); } finally { pwd.setText(""); } }
From source file:nDasJoWo.signapk.SignApk.java
License:Apache License
private static void writeSignatureBlock(CMSTypedData paramCMSTypedData, X509Certificate paramX509Certificate, PrivateKey paramPrivateKey, OutputStream paramOutputStream) throws IOException, CertificateEncodingException, OperatorCreationException, CMSException { ArrayList localArrayList = new ArrayList(1); localArrayList.add(paramX509Certificate); JcaCertStore localJcaCertStore = new JcaCertStore(localArrayList); CMSSignedDataGenerator localCMSSignedDataGenerator = new CMSSignedDataGenerator(); ContentSigner localContentSigner = new JcaContentSignerBuilder("SHA1withRSA") .setProvider(sBouncyCastleProvider).build(paramPrivateKey); localCMSSignedDataGenerator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder( new JcaDigestCalculatorProviderBuilder().setProvider(sBouncyCastleProvider).build()) .setDirectSignature(true).build(localContentSigner, paramX509Certificate)); localCMSSignedDataGenerator.addCertificates(localJcaCertStore); CMSSignedData localCMSSignedData = localCMSSignedDataGenerator.generate(paramCMSTypedData, false); ASN1InputStream localASN1InputStream = new ASN1InputStream(localCMSSignedData.getEncoded()); DEROutputStream localDEROutputStream = new DEROutputStream(paramOutputStream); localDEROutputStream.writeObject(localASN1InputStream.readObject()); }
From source file:net.ripe.rpki.commons.crypto.cms.RpkiSignedObjectBuilder.java
License:BSD License
private byte[] doGenerate(X509Certificate signingCertificate, PrivateKey privateKey, String signatureProvider, ASN1ObjectIdentifier contentTypeOid, ASN1Encodable encodableContent) throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, CertStoreException, CMSException, NoSuchProviderException, IOException, CertificateEncodingException, OperatorCreationException { byte[] subjectKeyIdentifier = X509CertificateUtil.getSubjectKeyIdentifier(signingCertificate); Validate.notNull(subjectKeyIdentifier, "certificate must contain SubjectKeyIdentifier extension"); CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); addSignerInfo(generator, privateKey, signatureProvider, signingCertificate); generator.addCertificates(new JcaCertStore(Collections.singleton(signingCertificate))); byte[] content = Asn1Util.encode(encodableContent); CMSSignedData data = generator.generate(new CMSProcessableByteArray(contentTypeOid, content), true); return data.getEncoded(); }
From source file:net.ripe.rpki.commons.provisioning.cms.ProvisioningCmsObjectBuilder.java
License:BSD License
private byte[] doGenerate(PrivateKey privateKey) throws CMSException, IOException, CertificateEncodingException, CRLException, OperatorCreationException { CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); addCertificateAndCrl(generator);/*from w w w.j a va 2s. c o m*/ addSignerInfo(generator, privateKey); CMSSignedData data = generator.generate( new CMSProcessableByteArray(CONTENT_TYPE, payloadContent.getBytes(Charset.forName("UTF-8"))), true); return data.getEncoded(); }
From source file:net.sf.assinafacil.AssinadorMSCAPI.java
License:Open Source License
@Override /***//www .j a va2s .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.keystore_explorer.crypto.signing.JarSigner.java
License:Open Source License
private static byte[] createSignatureBlock(byte[] toSign, PrivateKey privateKey, X509Certificate[] certificateChain, SignatureType signatureType, String tsaUrl, Provider provider) throws CryptoException { try {/*w w w . j av a 2 s.com*/ List<X509Certificate> certList = new ArrayList<X509Certificate>(); Collections.addAll(certList, certificateChain); DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider("BC") .build(); JcaContentSignerBuilder csb = new JcaContentSignerBuilder(signatureType.jce()) .setSecureRandom(SecureRandom.getInstance("SHA1PRNG")); if (provider != null) { csb.setProvider(provider); } JcaSignerInfoGeneratorBuilder siGeneratorBuilder = new JcaSignerInfoGeneratorBuilder(digCalcProv); // remove cmsAlgorithmProtect for compatibility reasons SignerInfoGenerator sigGen = siGeneratorBuilder.build(csb.build(privateKey), certificateChain[0]); final CMSAttributeTableGenerator sAttrGen = sigGen.getSignedAttributeTableGenerator(); sigGen = new SignerInfoGenerator(sigGen, new DefaultSignedAttributeTableGenerator() { @Override public AttributeTable getAttributes(@SuppressWarnings("rawtypes") Map parameters) { AttributeTable ret = sAttrGen.getAttributes(parameters); return ret.remove(CMSAttributes.cmsAlgorithmProtect); } }, sigGen.getUnsignedAttributeTableGenerator()); CMSSignedDataGenerator dataGen = new CMSSignedDataGenerator(); dataGen.addSignerInfoGenerator(sigGen); dataGen.addCertificates(new JcaCertStore(certList)); CMSSignedData signedData = dataGen.generate(new CMSProcessableByteArray(toSign), true); // now let TSA time-stamp the signature if (tsaUrl != null && !tsaUrl.isEmpty()) { signedData = addTimestamp(tsaUrl, signedData); } return signedData.getEncoded(); } catch (Exception ex) { throw new CryptoException(res.getString("SignatureBlockCreationFailed.exception.message"), ex); } }
From source file:org.apache.felix.deploymentadmin.itest.util.DPSigner.java
License:Apache License
private byte[] calculateSignatureBlock(PrivateKey privKey, X509Certificate cert, byte[] sfRawBytes) throws Exception { String signatureAlgorithm = getSignatureAlgorithm(privKey); DigestCalculatorProvider digestCalculatorProvider = new JcaDigestCalculatorProviderBuilder().build(); ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).build(privKey); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(digestCalculatorProvider).build(signer, cert)); gen.addCertificates(new JcaCertStore(Arrays.asList(cert))); CMSSignedData sigData = gen.generate(new CMSProcessableByteArray(sfRawBytes)); return sigData.getEncoded(); }
From source file:org.apache.kerby.pkix.SignedDataEngine.java
License:Apache License
static byte[] getSignedData(PrivateKey privateKey, X509Certificate certificate, byte[] dataToSign, String eContentType)/*w ww. ja v a 2 s.co m*/ throws IOException, OperatorCreationException, CertificateEncodingException, CMSException { if (Security.getProvider("BC") == null) { Security.addProvider(new BouncyCastleProvider()); } List certList = new ArrayList(); certList.add(certificate); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); gen.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC").build("SHA1withRSA", privateKey, certificate)); gen.addCertificates(certs); ASN1ObjectIdentifier asn1ObjectIdentifier = new ASN1ObjectIdentifier(eContentType); CMSTypedData msg = new CMSProcessableByteArray(asn1ObjectIdentifier, dataToSign); CMSSignedData s = gen.generate(msg, true); return s.getEncoded(); }