CertificateID certID = new CertificateID(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build().get(CertificateID.HASH_SHA1), new X509CertificateHolder(issuerCert.getEncoded()), currCert.getSerialNumber()); gen.addRequest(certID); OCSPReq ocspRequest = gen.build();
final DigestCalculatorProvider calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(); final CertificateID certificateId = new CertificateID(calculatorProviderBuilder.get(CertificateID.HASH_SHA1), new X509CertificateHolder(issuerCertificate.getEncoded()),
@SuppressWarnings(value = "unchecked") public static byte[] sign(Providers providers, SignedOutput out) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, CMSException, OperatorCreationException, CertificateEncodingException { ByteArrayOutputStream bodyOs = new ByteArrayOutputStream(); MessageBodyWriter writer = providers.getMessageBodyWriter(out.getType(), out.getGenericType(), null, out.getMediaType()); if (writer == null) { throw new WriterException(Messages.MESSAGES.failedToFindWriter(out.getType().getName())); } MultivaluedMapImpl<String, Object> bodyHeaders = new MultivaluedMapImpl<String, Object>(); bodyHeaders.add("Content-Type", out.getMediaType().toString()); writer.writeTo(out.getEntity(), out.getType(), out.getGenericType(), null, out.getMediaType(), bodyHeaders, bodyOs); CMSSignedDataGenerator signGen = new CMSSignedDataGenerator(); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(out.getPrivateKey()); signGen.addSignerInfoGenerator( new JcaSignerInfoGeneratorBuilder( new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()) .build(sha1Signer, out.getCertificate())); CMSTypedData content = new CMSProcessableByteArray(bodyOs.toByteArray()); CMSSignedData signedData = signGen.generate(content, true); return signedData.getEncoded(); } }
public void parse( InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { try { DigestCalculatorProvider digestCalculatorProvider = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(); CMSSignedDataParser parser = new CMSSignedDataParser(digestCalculatorProvider, new CloseShieldInputStream(stream)); try { CMSTypedStream content = parser.getSignedContent(); if (content == null) { throw new TikaException("cannot parse detached pkcs7 signature (no signed data to parse)"); } try (InputStream input = content.getContentStream()) { Parser delegate = context.get(Parser.class, EmptyParser.INSTANCE); delegate.parse(input, handler, metadata, context); } } finally { parser.close(); } } catch (OperatorCreationException e) { throw new TikaException("Unable to create DigestCalculatorProvider", e); } catch (CMSException e) { throw new TikaException("Unable to parse pkcs7 signed data", e); } }
protected SignatureHelper(Provider provider) { this.provider = provider; jcaDigestCalculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder(); if (provider != null) jcaDigestCalculatorProviderBuilder.setProvider(provider); }
/** * Method for creating CertificateID for OCSP request * @param signersCert * @param caCert * @return * @throws NoSuchAlgorithmException * @throws NoSuchProviderException * @throws CertificateEncodingException */ private CertificateID creatCertReq(X509Certificate signersCert, X509Certificate caCert) throws Exception { DigestCalculatorProvider dcp = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(); X509CertificateHolder caCertHolder = new X509CertificateHolder(caCert.getEncoded()); return new CertificateID(dcp.get(CertificateID.HASH_SHA1), caCertHolder, signersCert.getSerialNumber()); }
X509Certificate signingCertificate = getSigningCertificate(); //The chain of certificates that issued your signing certificate and so on Collection<X509Certificate;> certificateChain = getCertificateChain(); PrivateKey pk = getPrivateKey(); byte[] message = "SomeMessage".getBytes(); CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); certificateChain.add(signingCertificate); generator.addCertificates(new CollectionStore(certificateChain)); JcaDigestCalculatorProviderBuilder jcaDigestProvider = new JcaDigestCalculatorProviderBuilder(); jcaDigestProvider.setProvider(new BouncyCastleProvider()); JcaSignerInfoGeneratorBuilder singerInfoGenerator = new JcaSignerInfoGeneratorBuilder(jcaDigestProvider.build()); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); AsymmetricKeyParameter privateKeyParam = PrivateKeyFactory.createKey(pk.getEncoded()); ContentSigner cs = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyParam); SignerInfoGenerator sig = singerInfoGenerator.build(cs, signingCertificate); generator.addSignerInfoGenerator(sig); CMSSignedData data = generator.generate(new CMSProcessableByteArray(message), true);
private OCSPReq generateOCSPRequest(X509Certificate issuerCert, BigInteger serialNumber) throws CertificateEncodingException, OperatorCreationException, OCSPException, IOException { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build().get(CertificateID.HASH_SHA1), issuerCert, serialNumber)); BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis()); Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, true, new DEROctetString(nonce.toByteArray())); gen.setRequestExtensions(new Extensions(new Extension[]{ext})); sentNonce = ext.getExtnId().getEncoded(); return gen.build(); }
digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider( BouncyCastleProvider.PROVIDER_NAME).build(); } catch (OperatorCreationException e) {
protected boolean verify() throws SODException { try { /* verificar caminho de certificação sem ocsp/crl, aqui não é local para essas considerações */ X509CertificateHolder holder = (X509CertificateHolder) cms.getCertificates().getMatches(null).iterator().next(); // apenas o primeiro certificado (só tem 1) X509Certificate cert = (X509Certificate) get(holder.getEncoded()); SignerInformationStore signerInformationStore = cms.getSignerInfos(); SignerInformation signerInformation = (SignerInformation) signerInformationStore.getSigners().iterator().next(); // apenas 1 assinatura (só tem 1) if (!Util.isLeafCertificateValid(keystore, cert)){ return false; } /* verificar assinatura do cms */ ContentVerifierProvider contentVerifierProvider = new JcaContentVerifierProviderBuilder().setProvider(new BouncyCastleProvider()).build(cert); DigestCalculatorProvider digestCalculatorProvider = new JcaDigestCalculatorProviderBuilder().setProvider(new BouncyCastleProvider()).build(); SignatureAlgorithmIdentifierFinder signatureAlgorithmIdentifierFinder = new DefaultSignatureAlgorithmIdentifierFinder(); CMSSignatureAlgorithmNameGenerator signatureAlgorithmNameGenerator = new DefaultCMSSignatureAlgorithmNameGenerator(); SignerInformationVerifier signerInformationVerifier = new SignerInformationVerifier(signatureAlgorithmNameGenerator, signatureAlgorithmIdentifierFinder, contentVerifierProvider, digestCalculatorProvider); return signerInformation.verify(signerInformationVerifier); } catch (LeafCertificateValidationException | IOException | CertificateException | OperatorCreationException | CMSException ex) { throw new SODException("Não foi possivel verificar o SOD ("+ex.getMessage()+")", ex); } }
.setProvider(provider).build(); CertificateID id = new CertificateID( digCalcProv.get(CertificateID.HASH_SHA1),
private byte[] sign(byte[] data) throws SignatureException { CMSSignedDataGenerator cmsSignedDataGenerator = new CMSSignedDataGenerator(); try { 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); } }
DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(); JcaContentSignerBuilder csb = new JcaContentSignerBuilder(signatureType.jce()) .setSecureRandom(SecureRandom.getInstance("SHA1PRNG"));
@Override protected Object unmarshalInternal(InputStream is, Exchange exchange) throws Exception { CMSSignedDataParser sp; try { sp = new CMSSignedDataParser(new JcaDigestCalculatorProviderBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME).build(), is); } catch (CMSException e) { throw new CryptoCmsFormatException(getFormatErrorMessage(), e); } OutputStreamBuilder output = getOutputStream(sp, exchange); debugLog(sp); verify(sp, exchange); return output.build(); }
protected void unmarshalInternal(InputStream is, InputStream signature, Exchange exchange) throws Exception { CMSSignedDataParser sp; try { sp = new CMSSignedDataParser(new JcaDigestCalculatorProviderBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME).build(), new CMSTypedStream(is), signature); } catch (CMSException e) { throw new CryptoCmsFormatException(getFormatErrorMessage(), e); } try { // content must be read in order to calculate the hash for the // signature sp.getSignedContent().drain(); } catch (NullPointerException e) { // nullpointer exception is thrown // when the signed content is missing throw getContentMissingException(e); } LOG.debug("Signed data found"); debugLog(sp); verify(sp, exchange); }
public static byte[] createSignature(byte[] digest, SMimeDigestMethod digestMethod, PrivateKey privateKey, X509Certificate certificate) throws OxalisSecurityException { try { ASN1EncodableVector signedAttributes = new ASN1EncodableVector(); signedAttributes.add(new Attribute(CMSAttributes.contentType, new DERSet(digestMethod.getOid()))); signedAttributes.add(new Attribute(CMSAttributes.messageDigest, new DERSet(new DEROctetString(digest)))); signedAttributes.add(new Attribute(CMSAttributes.signingTime, new DERSet(new DERUTCTime(new Date())))); AttributeTable signedAttributesTable = new AttributeTable(signedAttributes); signedAttributesTable.toASN1EncodableVector(); DefaultSignedAttributeTableGenerator signedAttributeGenerator = new DefaultSignedAttributeTableGenerator(signedAttributesTable); /* Build the SignerInfo generator builder, that will build the generator... that will generate the SignerInformation... */ SignerInfoGeneratorBuilder signerInfoBuilder = new SignerInfoGeneratorBuilder( new JcaDigestCalculatorProviderBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME).build()); signerInfoBuilder.setSignedAttributeGenerator(signedAttributeGenerator); CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); JcaContentSignerBuilder contentSigner = new JcaContentSignerBuilder(digestMethod.getMethod()).setProvider(BouncyCastleProvider.PROVIDER_NAME); generator.addSignerInfoGenerator(signerInfoBuilder.build( contentSigner.build(privateKey), new X509CertificateHolder(certificate.getEncoded()))); generator.addCertificates(new JcaCertStore(Collections.singletonList(certificate))); return generator.generate(new CMSAbsentContent()).getEncoded(); } catch (CMSException | IOException | CertificateEncodingException | OperatorCreationException e) { throw new OxalisSecurityException(e.getMessage(), e); } } }
public static byte[] createSignature(byte[] digest, SMimeDigestMethod digestMethod, PrivateKey privateKey, X509Certificate certificate) throws OxalisSecurityException { try { ASN1EncodableVector signedAttributes = new ASN1EncodableVector(); signedAttributes.add(new Attribute(CMSAttributes.contentType, new DERSet(digestMethod.getOid()))); signedAttributes.add(new Attribute(CMSAttributes.messageDigest, new DERSet(new DEROctetString(digest)))); signedAttributes.add(new Attribute(CMSAttributes.signingTime, new DERSet(new DERUTCTime(new Date())))); AttributeTable signedAttributesTable = new AttributeTable(signedAttributes); signedAttributesTable.toASN1EncodableVector(); DefaultSignedAttributeTableGenerator signedAttributeGenerator = new DefaultSignedAttributeTableGenerator(signedAttributesTable); /* Build the SignerInfo generator builder, that will build the generator... that will generate the SignerInformation... */ SignerInfoGeneratorBuilder signerInfoBuilder = new SignerInfoGeneratorBuilder( new JcaDigestCalculatorProviderBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME).build()); signerInfoBuilder.setSignedAttributeGenerator(signedAttributeGenerator); CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); JcaContentSignerBuilder contentSigner = new JcaContentSignerBuilder(digestMethod.getMethod()).setProvider(BouncyCastleProvider.PROVIDER_NAME); generator.addSignerInfoGenerator(signerInfoBuilder.build( contentSigner.build(privateKey), new X509CertificateHolder(certificate.getEncoded()))); generator.addCertificates(new JcaCertStore(Collections.singletonList(certificate))); return generator.generate(new CMSAbsentContent()).getEncoded(); } catch (CMSException | IOException | CertificateEncodingException | OperatorCreationException e) { throw new OxalisSecurityException(e.getMessage(), e); } } }
/** Sign data and write the digital signature to 'out'. */ private static void writeSignatureBlock( CMSTypedData data, X509Certificate publicKey, PrivateKey privateKey, OutputStream out) throws IOException, CertificateEncodingException, OperatorCreationException, CMSException { ArrayList < X509Certificate > certList = new ArrayList < > (1); certList.add(publicKey); JcaCertStore certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner signer = new JcaContentSignerBuilder(getSignatureAlgorithm(publicKey)) .setProvider(sBouncyCastleProvider) .build(privateKey); gen.addSignerInfoGenerator( new JcaSignerInfoGeneratorBuilder( new JcaDigestCalculatorProviderBuilder() .setProvider(sBouncyCastleProvider) .build()) .setDirectSignature(true) .build(signer, 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()); } /**
public void parse( InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { try { DigestCalculatorProvider digestCalculatorProvider = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(); CMSSignedDataParser parser = new CMSSignedDataParser(digestCalculatorProvider, new CloseShieldInputStream(stream)); try { CMSTypedStream content = parser.getSignedContent(); if (content == null) { throw new TikaException("cannot parse detached pkcs7 signature (no signed data to parse)"); } try (InputStream input = content.getContentStream()) { Parser delegate = context.get(Parser.class, EmptyParser.INSTANCE); delegate.parse(input, handler, metadata, context); } } finally { parser.close(); } } catch (OperatorCreationException e) { throw new TikaException("Unable to create DigestCalculatorProvider", e); } catch (CMSException e) { throw new TikaException("Unable to parse pkcs7 signed data", e); } }
try { DigestCalculatorProvider digestCalculatorProvider = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(); CMSSignedDataParser parser = null; CMSTypedStream content = null;