List of usage examples for org.bouncycastle.cms CMSSignedData getEncoded
public byte[] getEncoded() throws IOException
From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java
License:Open Source License
@SuppressWarnings("unchecked") protected static String validarAssinaturaCMSeCarimboDeTempo(final byte[] digest, final String digestAlgorithm, final byte[] assinatura, Date dtAssinatura) throws InvalidKeyException, SecurityException, CRLException, CertificateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, AplicacaoException, ChainValidationException, IOException, Exception { String nome = validarAssinaturaCMS(digest, digestAlgorithm, assinatura, dtAssinatura); Map<String, byte[]> map = new HashMap<String, byte[]>(); map.put(digestAlgorithm, digest);//w w w. j a v a 2 s .com final CMSSignedData s = new CMSSignedData(map, assinatura); Collection ss = s.getSignerInfos().getSigners(); SignerInformation si = (SignerInformation) ss.iterator().next(); Attribute attr = si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken); CMSSignedData cmsTS = new CMSSignedData(attr.getAttrValues().getObjectAt(0).toASN1Primitive().getEncoded()); TimeStampToken tok = new TimeStampToken(cmsTS); Store cs = tok.getCertificates(); SignerId signer_id = tok.getSID(); BigInteger cert_serial_number = signer_id.getSerialNumber(); Collection certs = cs.getMatches(null); Iterator iter = certs.iterator(); X509Certificate certificate = null; while (iter.hasNext()) { X509Certificate cert = (X509Certificate) iter.next(); if (cert_serial_number != null) { if (cert.getSerialNumber().equals(cert_serial_number)) { certificate = cert; } } else { if (certificate == null) { certificate = cert; } } } tok.validate(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certificate)); // Nato: falta validar as CRLs do carimbo de tempo if (!Arrays.equals(tok.getTimeStampInfo().getMessageImprintDigest(), MessageDigest.getInstance("SHA1").digest(si.getSignature()))) { throw new Exception("Carimbo de tempo no confere com o resumo do documento"); } try { validarAssinaturaCMS(null, null, cmsTS.getEncoded(), tok.getTimeStampInfo().getGenTime()); } catch (Exception e) { throw new Exception("Carimbo de tempo invlido!", e); } return nome; }
From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java
License:Open Source License
protected static byte[] converterPkcs7EmCMSComCertificadosCRLsECarimboDeTempo(byte[] pkcs7) throws Exception { byte[] A_CP = converterPkcs7EmCMSComCertificadosECRLs(pkcs7); CMSSignedData A_T = TimeStamper.addTimestamp(new CMSSignedData(A_CP)); return A_T.getEncoded(); // verificarAssinaturaCMS(conteudo, A_T.getEncoded(), dtAssinatura); //// w w w . j a va 2 s .c om // addSignatureToPDF(conteudo, A_T.getEncoded()); // // FileOutputStream fout = new FileOutputStream( // "c:/trabalhos/java/sign.pdf"); // fout.write(conteudo); // fout.close(); // // FileOutputStream fout2 = new FileOutputStream( // "c:/trabalhos/java/sign.cms"); // fout2.write(A_T.getEncoded()); // fout2.close(); }
From source file:chapter9.SignedDataExample.java
/** * * @param args//from w ww .j av a2 s . c o 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 ww w. j ava2 s. com*/ 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 v a 2 s . co 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"); }
From source file:com.ackpdfbox.app.CreateSignatureBase.java
License:Apache License
/** * SignatureInterface implementation./* w w w . jav a2s . co 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. * * Use your favorite cryptographic library to implement PKCS #7 signature creation. */ @Override public byte[] sign(InputStream content) throws IOException { //TODO this method should be private 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:com.android.apksigner.core.internal.apk.v1.V1SchemeSigner.java
License:Apache License
private static byte[] generateSignatureBlock(SignerConfig signerConfig, byte[] signatureFileBytes) throws InvalidKeyException, CertificateEncodingException, SignatureException { JcaCertStore certs = new JcaCertStore(signerConfig.certificates); X509Certificate signerCert = signerConfig.certificates.get(0); String jcaSignatureAlgorithm = getJcaSignatureAlgorithm(signerCert.getPublicKey(), signerConfig.signatureDigestAlgorithm); try {/*from w ww. jav a2s . co m*/ ContentSigner signer = new JcaContentSignerBuilder(jcaSignatureAlgorithm) .build(signerConfig.privateKey); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); gen.addSignerInfoGenerator( new SignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build(), SignerInfoSignatureAlgorithmFinder.INSTANCE).setDirectSignature(true).build(signer, new JcaX509CertificateHolder(signerCert))); gen.addCertificates(certs); CMSSignedData sigData = gen.generate(new CMSProcessableByteArray(signatureFileBytes), false); ByteArrayOutputStream out = new ByteArrayOutputStream(); try (ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded())) { DEROutputStream dos = new DEROutputStream(out); dos.writeObject(asn1.readObject()); } return out.toByteArray(); } catch (OperatorCreationException | CMSException | IOException e) { throw new SignatureException("Failed to generate signature", e); } }
From source file:com.android.builder.internal.packaging.sign.SignatureExtension.java
License:Apache License
/** * Computes the digital signature of an array of data. * * @param data the data/*from w w w.ja va 2 s.c o m*/ * @return the digital signature * @throws IOException failed to read/write signature data * @throws CertificateEncodingException failed to sign the data * @throws OperatorCreationException failed to sign the data * @throws CMSException failed to sign the data */ private byte[] computePkcs7Signature(@NonNull byte[] data) throws IOException, CertificateEncodingException, OperatorCreationException, CMSException { CMSProcessableByteArray cmsData = new CMSProcessableByteArray(data); ArrayList<X509Certificate> certList = new ArrayList<>(); certList.add(mCertificate); JcaCertStore certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); String signatureAlgName = mSignatureAlgorithm.signatureAlgorithmName(mDigestAlgorithm); ContentSigner shaSigner = new JcaContentSignerBuilder(signatureAlgName).build(mPrivateKey); gen.addSignerInfoGenerator( new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build()) .setDirectSignature(true).build(shaSigner, mCertificate)); gen.addCertificates(certs); CMSSignedData sigData = gen.generate(cmsData, false); ByteArrayOutputStream outputBytes = new ByteArrayOutputStream(); /* * DEROutputStream is not closeable! OMG! */ DEROutputStream dos = null; try (ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded())) { dos = new DEROutputStream(outputBytes); dos.writeObject(asn1.readObject()); DEROutputStream toClose = dos; dos = null; toClose.close(); } catch (IOException e) { if (dos != null) { try { dos.close(); } catch (IOException ee) { e.addSuppressed(ee); } } } return outputBytes.toByteArray(); }
From source file:com.android.builder.signing.SignedJarApkCreator.java
License:Apache License
/** Write the certificate file with a digital signature. */ private void writeSignatureBlock(CMSTypedData data, X509Certificate publicKey) throws IOException, CertificateEncodingException, OperatorCreationException, CMSException { ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>(); certList.add(publicKey);//from w ww . j a v a 2 s. c o m JcaCertStore certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner sha1Signer = new JcaContentSignerBuilder( mSignatureAlgorithm.signatureAlgorithmName(mDigestAlgorithm)).build(mKey); gen.addSignerInfoGenerator( new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build()) .setDirectSignature(true).build(sha1Signer, publicKey)); gen.addCertificates(certs); CMSSignedData sigData = gen.generate(data, false); try (ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded())) { DEROutputStream dos = new DEROutputStream(mOutputJar); try { dos.writeObject(asn1.readObject()); } finally { dos.flush(); dos.close(); } } }
From source file:com.android.builder.signing.SignedJarBuilder.java
License:Apache License
/** Write the certificate file with a digital signature. */ private void writeSignatureBlock(CMSTypedData data, X509Certificate publicKey, PrivateKey privateKey) throws IOException, CertificateEncodingException, OperatorCreationException, CMSException { ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>(); certList.add(publicKey);// w w w . ja v a 2s.c o m JcaCertStore certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1with" + privateKey.getAlgorithm()) .build(privateKey); gen.addSignerInfoGenerator( new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().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(mOutputJar); dos.writeObject(asn1.readObject()); dos.flush(); dos.close(); asn1.close(); }