List of usage examples for org.bouncycastle.cms CMSSignedDataGenerator CMSSignedDataGenerator
public CMSSignedDataGenerator()
From source file:assinaBc.java
CMSSignedDataGenerator setUpProvider(final KeyStore keystore) throws Exception { Security.addProvider(new BouncyCastleProvider()); Certificate[] certchain = (Certificate[]) keystore.getCertificateChain(KEY_ALIAS_IN_KEYSTORE); final List<Certificate> certlist = new ArrayList<>(); for (int i = 0, length = certchain == null ? 0 : certchain.length; i < length; i++) { certlist.add(certchain[i]);/*from ww w.j a v a 2s. c o m*/ } Store certstore = new JcaCertStore(certlist); Certificate cert = keystore.getCertificate(KEY_ALIAS_IN_KEYSTORE); ContentSigner signer = new JcaContentSignerBuilder(SIGNATUREALGO).setProvider("BC") .build((PrivateKey) (keystore.getKey(KEY_ALIAS_IN_KEYSTORE, KEYSTORE_PASSWORD.toCharArray()))); CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); generator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder( new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(signer, (X509Certificate) cert)); generator.addCertificates(certstore); return generator; }
From source file:CreateSignatureBase.java
License:Apache License
/** * SignatureInterface implementation.//from w w w .j a v a2s. c o m * * This method will be called from inside of the pdfbox and create the PKCS #7 signature. * The given InputStream contains the bytes that are given by the byte range. * * This method is for internal use only. <-- TODO this method should be private * * Use your favorite cryptographic library to implement PKCS #7 signature creation. */ @Override public byte[] sign(InputStream content) throws IOException { try { List<Certificate> certList = new ArrayList<Certificate>(); certList.add(certificate); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); org.bouncycastle.asn1.x509.Certificate cert = org.bouncycastle.asn1.x509.Certificate .getInstance(ASN1Primitive.fromByteArray(certificate.getEncoded())); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA256WithRSA").build(privateKey); gen.addSignerInfoGenerator( new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build()) .build(sha1Signer, new X509CertificateHolder(cert))); gen.addCertificates(certs); CMSProcessableInputStream msg = new CMSProcessableInputStream(content); CMSSignedData signedData = gen.generate(msg, false); if (tsaClient != null) { signedData = signTimeStamps(signedData); } return signedData.getEncoded(); } catch (GeneralSecurityException e) { throw new IOException(e); } catch (CMSException e) { throw new IOException(e); } catch (TSPException e) { throw new IOException(e); } catch (OperatorCreationException e) { throw new IOException(e); } }
From source file:createSod.java
License:Open Source License
/** * @param args/*from w w w . ja v a 2 s .c o m*/ * @throws CMSException */ public static void main(String[] args) throws Exception { try { CommandLine options = verifyArgs(args); String privateKeyLocation = options.getOptionValue("privatekey"); String keyPassword = options.getOptionValue("keypass"); String certificate = options.getOptionValue("certificate"); String sodContent = options.getOptionValue("content"); String sod = ""; if (options.hasOption("out")) { sod = options.getOptionValue("out"); } // CHARGEMENT DU FICHIER PKCS#12 KeyStore ks = null; char[] password = null; Security.addProvider(new BouncyCastleProvider()); try { ks = KeyStore.getInstance("PKCS12"); // Password pour le fichier personnal_nyal.p12 password = keyPassword.toCharArray(); ks.load(new FileInputStream(privateKeyLocation), password); } catch (Exception e) { System.out.println("Erreur: fichier " + privateKeyLocation + " n'est pas un fichier pkcs#12 valide ou passphrase incorrect"); return; } // RECUPERATION DU COUPLE CLE PRIVEE/PUBLIQUE ET DU CERTIFICAT PUBLIQUE X509Certificate cert = null; PrivateKey privatekey = null; PublicKey publickey = null; try { Enumeration en = ks.aliases(); String ALIAS = ""; Vector vectaliases = new Vector(); while (en.hasMoreElements()) vectaliases.add(en.nextElement()); String[] aliases = (String[]) (vectaliases.toArray(new String[0])); for (int i = 0; i < aliases.length; i++) if (ks.isKeyEntry(aliases[i])) { ALIAS = aliases[i]; break; } privatekey = (PrivateKey) ks.getKey(ALIAS, password); cert = (X509Certificate) ks.getCertificate(ALIAS); publickey = ks.getCertificate(ALIAS).getPublicKey(); } catch (Exception e) { e.printStackTrace(); return; } // Chargement du certificat partir du fichier InputStream inStream = new FileInputStream(certificate); CertificateFactory cf = CertificateFactory.getInstance("X.509"); cert = (X509Certificate) cf.generateCertificate(inStream); inStream.close(); // Chargement du fichier qui va tre sign File file_to_sign = new File(sodContent); byte[] buffer = new byte[(int) file_to_sign.length()]; DataInputStream in = new DataInputStream(new FileInputStream(file_to_sign)); in.readFully(buffer); in.close(); // Chargement des certificats qui seront stocks dans le fichier .p7 // Ici, seulement le certificat personnal_nyal.cer sera associ. // Par contre, la chane des certificats non. ArrayList certList = new ArrayList(); certList.add(cert); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); CMSSignedDataGenerator signGen = new CMSSignedDataGenerator(); // privatekey correspond notre cl prive rcupre du fichier PKCS#12 // cert correspond au certificat publique personnal_nyal.cer // Le dernier argument est l'algorithme de hachage qui sera utilis signGen.addSigner(privatekey, cert, CMSSignedDataGenerator.DIGEST_SHA1); signGen.addCertificatesAndCRLs(certs); CMSProcessable content = new CMSProcessableByteArray(buffer); // Generation du fichier CMS/PKCS#7 // L'argument deux permet de signifier si le document doit tre attach avec la signature // Valeur true: le fichier est attach (c'est le cas ici) // Valeur false: le fichier est dtach CMSSignedData signedData = signGen.generate(content, true, "BC"); byte[] signeddata = signedData.getEncoded(); // Ecriture du buffer dans un fichier. if (sod.equals("")) { System.out.print(signeddata.toString()); } else { FileOutputStream envfos = new FileOutputStream(sod); envfos.write(signeddata); envfos.close(); } } catch (OptionException oe) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(NAME, getOptions()); System.exit(-1); } catch (Exception e) { e.printStackTrace(); return; } }
From source file:be.e_contract.mycarenet.certra.cms.CMSSigner.java
License:Open Source License
private byte[] sign(byte[] data) throws SignatureException { CMSSignedDataGenerator cmsSignedDataGenerator = new CMSSignedDataGenerator(); try {/*from w w w.j a v a2 s . c o m*/ ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256withRSA").build(this.privateKey); cmsSignedDataGenerator.addSignerInfoGenerator( new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME).build()).build(contentSigner, this.certificateChain.get(0))); for (X509Certificate certificate : this.certificateChain) { cmsSignedDataGenerator.addCertificate(new X509CertificateHolder(certificate.getEncoded())); } CMSTypedData cmsTypedData = new CMSProcessableByteArray(data); CMSSignedData cmsSignedData = cmsSignedDataGenerator.generate(cmsTypedData, true); return cmsSignedData.getEncoded(); } catch (Exception e) { throw new SignatureException(e); } }
From source file:be.e_contract.mycarenet.etee.Sealer.java
License:Open Source License
private byte[] sign(byte[] data, boolean includeCertificate) throws OperatorCreationException, CertificateEncodingException, CMSException, IOException { CMSSignedDataGenerator cmsSignedDataGenerator = new CMSSignedDataGenerator(); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); AsymmetricKeyParameter privKeyParams = PrivateKeyFactory .createKey(this.authenticationPrivateKey.getEncoded()); ContentSigner contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privKeyParams); cmsSignedDataGenerator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder( new JcaDigestCalculatorProviderBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME).build()) .build(contentSigner, this.authenticationCertificate)); if (includeCertificate) { cmsSignedDataGenerator/*ww w . j a v a 2 s . co m*/ .addCertificate(new X509CertificateHolder(this.authenticationCertificate.getEncoded())); } CMSTypedData cmsTypedData = new CMSProcessableByteArray(data); CMSSignedData cmsSignedData = cmsSignedDataGenerator.generate(cmsTypedData, true); return cmsSignedData.getEncoded(); }
From source file:be.fedict.eid.applet.service.signer.cms.AbstractCMSSignatureService.java
License:Open Source License
private CMSSignedDataGenerator createCMSSignedDataGenerator(List<X509Certificate> signingCertificateChain) throws NoSuchAlgorithmException { CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); if (null != signingCertificateChain) { X509Certificate signerCertificate = signingCertificateChain.get(0); PrivateKey dummyPrivateKey = new DummyPrivateKey(); generator.addSigner(dummyPrivateKey, signerCertificate, CMSSignedDataGenerator.DIGEST_SHA1); List<X509Certificate> certList = new LinkedList<X509Certificate>(); certList.add(signerCertificate); CertStore certStore;/*from w w w .j a v a 2 s .co m*/ try { certStore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList)); } catch (InvalidAlgorithmParameterException e) { throw new NoSuchAlgorithmException(e); } try { generator.addCertificatesAndCRLs(certStore); } catch (CertStoreException e) { throw new RuntimeException(e); } catch (CMSException e) { throw new RuntimeException(e); } } return generator; }
From source file:br.gov.frameworkdemoiselle.certificate.signer.pkcs7.bc.CAdESSigner.java
License:Open Source License
/** * Mtodo de assinatura de dados e gerao do pacote PKCS7 Assina apenas com * o contedo do tipo DATA: OID ContentType 1.2.840.113549.1.9.3 = OID Data * 1.2.840.113549.1.7.1 Utiliza o algoritmo da propriedade algorithm. Caso * essa propriedade no esteja setada, o algoritmo do enum * {@link SignerAlgorithmEnum.DEFAULT} ser usado. Para este mtodo * necessrio informar o contedo, a chave privada e um certificado digital * padro ICP-Brasil.//w ww. j ava2s . c o m * * @param content Contedo a ser assinado. TODO: Implementar co-assinaturas, * informar a poltica de assinatura * @return */ @Override public byte[] signer(byte[] content) { Security.addProvider(new BouncyCastleProvider()); if (this.certificate == null && this.certificateChain != null && this.certificateChain.length > 0) { this.certificate = (X509Certificate) this.certificateChain[0]; } this.validateForSigner(content); if (this.certificateChain == null || this.certificateChain.length <= 1) { this.certificateChain = CAManager.getInstance().getCertificateChainArray(this.certificate); } //Adiciona o atributo de identificacao da politica SignaturePolicyIdentifier signaturePolicyIdentifier = new SignaturePolicyIdentifier(); signaturePolicyIdentifier.setSignaturePolicyId(this.signaturePolicy.getSignaturePolicyId()); this.addAttribute(signaturePolicyIdentifier); //Adiciona o astributo certificado de assinatura boolean addSigningCertificateAttribute = true; for (Attribute attribute : this.getAttributes()) { if (attribute instanceof SigningCertificate) { addSigningCertificateAttribute = false; break; } } if (addSigningCertificateAttribute) { SigningCertificate signingCertificateAttribute = this.signaturePolicy .getSigningCertificateAttribute(this.certificate); this.addAttribute(signingCertificateAttribute); } this.setCertificate((X509Certificate) certificateChain[0]); if (certificateChain.length == 1) { throw new SignerException("Impossivel extrair a cadeia de confianca do certificado"); } String algorithmHashOID = null; String algorithmEncryptationOID = null; if (this.pkcs1 != null && this.pkcs1.getAlgorithm() != null && this.pkcs1.getAlgorithm().trim().length() > 0) { algorithmHashOID = SignerAlgorithmEnum.valueOf(this.pkcs1.getAlgorithm()).getOIDAlgorithmHash(); algorithmEncryptationOID = SignerAlgorithmEnum.valueOf(this.pkcs1.getAlgorithm()) .getOIDAlgorithmCipher(); } else { algorithmHashOID = this.signaturePolicy.getSignerAlgorithm().getOIDAlgorithmHash(); algorithmEncryptationOID = this.signaturePolicy.getSignerAlgorithm().getOIDAlgorithmCipher(); } byte[] result = null; CMSSignedDataGenerator signedDataGenerator = new CMSSignedDataGenerator(); try { signedDataGenerator.addCertificatesAndCRLs(this.generatedCertStore()); } catch (CertStoreException e) { throw new SignerException(e); } catch (CMSException e) { throw new SignerException(e); } // Valida o certificado usando a politica de certificacao this.signaturePolicy.validate(this.certificate, this.pkcs1.getPrivateKey()); //Recupera o(s) certificado(s) de confianca para validacao Collection<X509Certificate> trustedCas = CAManager.getInstance() .getSignaturePolicyRootCAs(signaturePolicy.getSignaturePolicyId().getSigPolicyId()); //Efetua a validacao das cadeias do certificado baseado na politica CAManager.getInstance().validateRootCAs(trustedCas, certificate); AttributeTable signedTable = this.mountSignedTable(); AttributeTable unsignedTable = this.mountUnsignedTable(); signedDataGenerator.addSigner(this.pkcs1.getPrivateKey(), this.certificate, algorithmEncryptationOID, algorithmHashOID, signedTable, unsignedTable); try { CMSProcessable processable = null; if (content == null) { processable = new CMSAbsentContent(); } else { processable = new CMSProcessableByteArray(content); } CMSSignedData signedData = signedDataGenerator.generate(CMSSignedDataGenerator.DATA, processable, this.attached, this.getProviderName(), true); result = signedData.getEncoded(); } catch (IOException e) { throw new SignerException(e); } catch (NoSuchAlgorithmException e) { throw new SignerException(e); } catch (NoSuchProviderException e) { throw new SignerException(e); } catch (CMSException e) { throw new SignerException(e); } return result; }
From source file:chapter9.SignedDataExample.java
/** * * @param args/*w w w .j a va 2s . co m*/ * @throws Exception */ public static void main(String[] args) throws Exception { KeyStore credentials = Utils.createCredentials(); PrivateKey key = (PrivateKey) credentials.getKey(Utils.END_ENTITY_ALIAS, Utils.KEY_PASSWD); Certificate[] chain = credentials.getCertificateChain(Utils.END_ENTITY_ALIAS); CertStore certsAndCRLs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(Arrays.asList(chain)), CryptoDefs.Provider.BC.getName()); X509Certificate cert = (X509Certificate) chain[0]; // Set up the generator CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); gen.addSigner(key, cert, CMSSignedDataGenerator.DIGEST_SHA224); gen.addCertificatesAndCRLs(certsAndCRLs); // Create the signed-data object CMSProcessable data = new CMSProcessableByteArray("Hello World!!".getBytes()); CMSSignedData signed = gen.generate(data, CryptoDefs.Provider.BC.getName()); // Re-create signed = new CMSSignedData(data, signed.getEncoded()); // Verification step X509Certificate rootCert = (X509Certificate) credentials.getCertificate(Utils.ROOT_ALIAS); if (isValid(signed, rootCert)) System.out.println("verification succeeded!!"); else System.out.println("verification failed!!"); }
From source file:cn.ieclipse.pde.signer.util.BcpSigner.java
License:Apache License
/** Sign data and write the digital signature to 'out'. */ private static void writeSignatureBlock(CMSTypedData data, X509Certificate publicKey, PrivateKey privateKey, OutputStream out)/*from w w w.ja v a2 s . c om*/ throws IOException, CertificateEncodingException, OperatorCreationException, CMSException { ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>(1); certList.add(publicKey); JcaCertStore certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(sBouncyCastleProvider) .build(privateKey); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder( new JcaDigestCalculatorProviderBuilder().setProvider(sBouncyCastleProvider).build()) .setDirectSignature(true).build(sha1Signer, publicKey)); gen.addCertificates(certs); CMSSignedData sigData = gen.generate(data, false); ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded()); DEROutputStream dos = new DEROutputStream(out); dos.writeObject(asn1.readObject()); }
From source file:com.aaasec.sigserv.csspsupport.pdfbox.CreateSignature.java
License:EUPL
/** * <p>/*w w w.ja va2 s . c o m*/ * SignatureInterface implementation. * </p> * * <p> * This method will be called from inside of the pdfbox and create the pkcs7 * signature. The given InputStream contains the bytes that are provided by * the byte range. * </p> * * <p> * This method is for internal use only. * </p> * * <p> * Here the user should use his favorite cryptographic library and implement * a pkcs7 signature creation. * </p> */ public byte[] sign(InputStream content) throws SignatureException, IOException { List<Certificate> certList = Arrays.asList(cert); CMSProcessableInputStream input = new CMSProcessableInputStream(content); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); CertStore certStore = null; try { Store certs = new JcaCertStore(certList); certStore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), provider); gen.addSigner(privKey, (X509Certificate) certList.get(0), CMSSignedGenerator.DIGEST_SHA256); gen.addCertificates(certs); CMSSignedData signedData = gen.generate(input, false, provider); model.setSignedData(signedData); PdfBoxSigUtil.parseSignedData(model); return signedData.getEncoded(); } catch (Exception e) { // should be handled System.err.println("Error while creating pkcs7 signature."); e.printStackTrace(); } throw new RuntimeException("Problem while preparing signature"); }