org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder Java Examples

The following examples show how to use org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SignHelper.java    From Launcher with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates the beast that can actually sign the data (for JKS, for other make it).
 */
public static CMSSignedDataGenerator createSignedDataGenerator(KeyStore keyStore, String keyAlias, String signAlgo, String keyPassword) throws KeyStoreException, OperatorCreationException, CertificateEncodingException, UnrecoverableKeyException, NoSuchAlgorithmException, CMSException {
    List<Certificate> certChain = new ArrayList<>(Arrays.asList(keyStore.getCertificateChain(keyAlias)));
    @SuppressWarnings("rawtypes")
    Store certStore = new JcaCertStore(certChain);
    Certificate cert = keyStore.getCertificate(keyAlias);
    PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAlias, keyPassword != null ? keyPassword.toCharArray() : null);
    ContentSigner signer = new JcaContentSignerBuilder(signAlgo).setProvider("BC").build(privateKey);
    CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
    DigestCalculatorProvider dcp = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build();
    SignerInfoGenerator sig = new JcaSignerInfoGeneratorBuilder(dcp).build(signer, (X509Certificate) cert);
    generator.addSignerInfoGenerator(sig);
    generator.addCertificates(certStore);
    return generator;
}
 
Example #2
Source File: CreateMultipleVisualizations.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * Copy of <code>org.apache.pdfbox.examples.signature.CreateSignatureBase.sign(InputStream)</code>
 * from the pdfbox examples artifact.
 */
@Override
public byte[] sign(InputStream content) throws IOException {
    try
    {
        List<Certificate> certList = new ArrayList<>();
        certList.addAll(Arrays.asList(chain));
        Store<?> certs = new JcaCertStore(certList);
        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
        org.bouncycastle.asn1.x509.Certificate cert = org.bouncycastle.asn1.x509.Certificate.getInstance(chain[0].getEncoded());
        ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA256WithRSA").build(pk);
        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);
        return signedData.getEncoded();
    }
    catch (GeneralSecurityException | CMSException | OperatorCreationException e)
    {
        throw new IOException(e);
    }
}
 
Example #3
Source File: PdfPKCS7.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Checks if OCSP revocation refers to the document signing certificate.
 * @return true if it checks false otherwise
 * @since	2.1.6
 */
public boolean isRevocationValid() {
    if (basicResp == null)
        return false;
    if (signCerts.size() < 2)
        return false;
    try {
        X509Certificate[] cs = (X509Certificate[])getSignCertificateChain();
        SingleResp sr = basicResp.getResponses()[0];
        CertificateID cid = sr.getCertID();
        X509Certificate sigcer = getSigningCertificate();
        X509Certificate isscer = cs[1];
        CertificateID tis = new CertificateID(
           new JcaDigestCalculatorProviderBuilder().build().get(CertificateID.HASH_SHA1), new JcaX509CertificateHolder(isscer), sigcer.getSerialNumber());
        return tis.equals(cid);
    }
    catch (Exception ex) {
    }
    return false;
}
 
Example #4
Source File: OcspClientBouncyCastle.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Generates an OCSP request using BouncyCastle.
 * @param issuerCert	certificate of the issues
 * @param serialNumber	serial number
 * @return	an OCSP request
 * @throws OCSPException
 * @throws IOException
 */
private static OCSPReq generateOCSPRequest(X509Certificate issuerCert, BigInteger serialNumber) throws OCSPException, IOException, OperatorException, CertificateEncodingException {
    //Add provider BC
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    
    JcaDigestCalculatorProviderBuilder digestCalculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder();
    DigestCalculatorProvider digestCalculatorProvider = digestCalculatorProviderBuilder.build();
    DigestCalculator digestCalculator = digestCalculatorProvider.get(CertificateID.HASH_SHA1);
    // Generate the id for the certificate we are looking for
    CertificateID id = new CertificateID(digestCalculator, new JcaX509CertificateHolder(issuerCert), serialNumber);
    
    // basic request generation with nonce
    OCSPReqBuilder gen = new OCSPReqBuilder();
    
    gen.addRequest(id);
    
    // create details for nonce extension
    Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString(new DEROctetString(PdfEncryption.createDocumentId()).getEncoded()));
    gen.setRequestExtensions(new Extensions(new Extension[]{ext}));
    
    return gen.build();
}
 
Example #5
Source File: CmsSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public byte[] sign(Credential signatureCredential, byte[] byteToSign, Map<String, Object> options) throws TechnicalConnectorException {
   byte[] contentToSign = ArrayUtils.clone(byteToSign);
   Map<String, Object> optionMap = new HashMap();
   if (options != null) {
      optionMap.putAll(options);
   }

   this.validateInput(signatureCredential, contentToSign);

   try {
      CMSTypedData content = new CMSProcessableByteArray(contentToSign);
      CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
      String signatureAlgorithm = (String)SignatureUtils.getOption("signatureAlgorithm", optionMap, "Sha1WithRSA");
      JcaSignerInfoGeneratorBuilder signerInfoGeneratorBuilder = new JcaSignerInfoGeneratorBuilder((new JcaDigestCalculatorProviderBuilder()).build());
      ContentSigner contentSigner = (new JcaContentSignerBuilder(signatureAlgorithm)).build(signatureCredential.getPrivateKey());
      CMSAttributeTableGenerator cmsAttributeTableGenerator = (CMSAttributeTableGenerator)SignatureUtils.getOption("signedAttributeGenerator", optionMap, new DefaultSignedAttributeTableGenerator());
      signerInfoGeneratorBuilder.setSignedAttributeGenerator(cmsAttributeTableGenerator);
      generator.addSignerInfoGenerator(signerInfoGeneratorBuilder.build(contentSigner, signatureCredential.getCertificate()));
      Certificate[] certificateChain = signatureCredential.getCertificateChain();
      if (certificateChain != null && certificateChain.length > 0) {
         generator.addCertificates(new JcaCertStore(Arrays.asList(certificateChain)));
      }

      boolean encapsulate = (Boolean)SignatureUtils.getOption("encapsulate", optionMap, Boolean.FALSE);
      return generator.generate(content, encapsulate).getEncoded();
   } catch (Exception var14) {
      LOG.error(var14.getMessage(), var14);
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_SIGNATURE, var14, new Object[]{var14.getClass().getSimpleName() + " : " + var14.getMessage()});
   }
}
 
Example #6
Source File: BouncyCastleCrypto.java    From tutorials with MIT License 5 votes vote down vote up
public static byte[] signData(byte[] data, final X509Certificate signingCertificate, final PrivateKey signingKey) throws CertificateEncodingException, OperatorCreationException, CMSException, IOException {
    byte[] signedMessage = null;
    List<X509Certificate> certList = new ArrayList<X509Certificate>();
    CMSTypedData cmsData = new CMSProcessableByteArray(data);
    certList.add(signingCertificate);
    Store certs = new JcaCertStore(certList);
    CMSSignedDataGenerator cmsGenerator = new CMSSignedDataGenerator();
    ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256withRSA").build(signingKey);
    cmsGenerator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(contentSigner, signingCertificate));
    cmsGenerator.addCertificates(certs);
    CMSSignedData cms = cmsGenerator.generate(cmsData, true);
    signedMessage = cms.getEncoded();
    return signedMessage;
}
 
Example #7
Source File: SignatureBlockGenerator.java    From fdroidclient with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Sign the given content using the private and public keys from the keySet, and return the encoded CMS (PKCS#7) data.
 * Use of direct signature and DER encoding produces a block that is verifiable by Android recovery programs.
 */
public static byte[] generate(KeySet keySet, byte[] content) {
    try {
        List certList = new ArrayList();
        CMSTypedData msg = new CMSProcessableByteArray(content);

        certList.add(keySet.getPublicKey());

        Store certs = new JcaCertStore(certList);

        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();

        JcaContentSignerBuilder jcaContentSignerBuilder = new JcaContentSignerBuilder(keySet.getSignatureAlgorithm()).setProvider("BC");
        ContentSigner sha1Signer = jcaContentSignerBuilder.build(keySet.getPrivateKey());

        JcaDigestCalculatorProviderBuilder jcaDigestCalculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder().setProvider("BC");
        DigestCalculatorProvider digestCalculatorProvider = jcaDigestCalculatorProviderBuilder.build();

        JcaSignerInfoGeneratorBuilder jcaSignerInfoGeneratorBuilder = new JcaSignerInfoGeneratorBuilder(digestCalculatorProvider);
        jcaSignerInfoGeneratorBuilder.setDirectSignature(true);
        SignerInfoGenerator signerInfoGenerator = jcaSignerInfoGeneratorBuilder.build(sha1Signer, keySet.getPublicKey());

        gen.addSignerInfoGenerator(signerInfoGenerator);

        gen.addCertificates(certs);

        CMSSignedData sigData = gen.generate(msg, false);
        return sigData.toASN1Structure().getEncoded("DER");

    } catch (Exception x) {
        throw new RuntimeException(x.getMessage(), x);
    }
}
 
Example #8
Source File: OCSPFuncTest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static OCSPReq generateOCSPRequest (final X509Certificate aIssuerCert,
                                           final BigInteger aCheckSerialNumber) throws OCSPException
{
  try
  {
    final DigestCalculatorProvider aDigestCalculatorProvider = new JcaDigestCalculatorProviderBuilder ().setProvider (PBCProvider.getProvider ())
                                                                                                        .build ();
    final DigestCalculator aDigestCalculator = aDigestCalculatorProvider.get (CertificateID.HASH_SHA1);

    // CertID structure is used to uniquely identify certificates that are the
    // subject of an OCSP request or response and has an ASN.1 definition.
    // CertID structure is defined in RFC 2560
    final CertificateID aCertificateID = new JcaCertificateID (aDigestCalculator, aIssuerCert, aCheckSerialNumber);

    // create details for nonce extension. The nonce extension is used to bind
    // a request to a response to prevent replay attacks. As the name implies,
    // the nonce value is something that the client should only use once
    // within a reasonably small period.
    final BigInteger aNonce = BigInteger.valueOf (System.nanoTime ());

    // to create the request Extension
    final Extensions aExtensions = new Extensions (new Extension (OCSPObjectIdentifiers.id_pkix_ocsp_nonce,
                                                                  false,
                                                                  new DEROctetString (aNonce.toByteArray ())));

    // basic request generation with nonce
    final OCSPReqBuilder aBuilder = new OCSPReqBuilder ();
    aBuilder.addRequest (aCertificateID);
    // Extension to the whole request
    aBuilder.setRequestExtensions (aExtensions);
    return aBuilder.build ();
  }
  catch (final OperatorCreationException | CertificateEncodingException ex)
  {
    throw new IllegalStateException (ex);
  }
}
 
Example #9
Source File: ZipUtils.java    From isu with GNU General Public License v3.0 5 votes vote down vote up
/** 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());
}
 
Example #10
Source File: V1SchemeSigner.java    From walle with Apache License 2.0 5 votes vote down vote up
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 {
        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);
    }
}
 
Example #11
Source File: SignedJarBuilder.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/** 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);
    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();
}
 
Example #12
Source File: LocalSignedJarBuilder.java    From atlas with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    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();
}
 
Example #13
Source File: SignHelper.java    From Launcher with GNU General Public License v3.0 5 votes vote down vote up
public static CMSSignedDataGenerator createSignedDataGenerator(PrivateKey privateKey, Certificate cert, List<Certificate> certChain, String signAlgo) throws OperatorCreationException, CertificateEncodingException, CMSException {
    @SuppressWarnings("rawtypes")
    Store certStore = new JcaCertStore(certChain);
    ContentSigner signer = new JcaContentSignerBuilder(signAlgo).setProvider("BC").build(privateKey);
    CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
    DigestCalculatorProvider dcp = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build();
    SignerInfoGenerator sig = new JcaSignerInfoGeneratorBuilder(dcp).build(signer, (X509Certificate) cert);
    generator.addSignerInfoGenerator(sig);
    generator.addCertificates(certStore);
    return generator;
}
 
Example #14
Source File: CmsSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public byte[] sign(Credential signatureCredential, byte[] byteToSign, Map<String, Object> options) throws TechnicalConnectorException {
   byte[] contentToSign = ArrayUtils.clone(byteToSign);
   Map<String, Object> optionMap = new HashMap();
   if (options != null) {
      optionMap.putAll(options);
   }

   this.validateInput(signatureCredential, contentToSign);

   try {
      CMSTypedData content = new CMSProcessableByteArray(contentToSign);
      CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
      String signatureAlgorithm = (String)SignatureUtils.getOption("signatureAlgorithm", optionMap, "Sha1WithRSA");
      JcaSignerInfoGeneratorBuilder signerInfoGeneratorBuilder = new JcaSignerInfoGeneratorBuilder((new JcaDigestCalculatorProviderBuilder()).build());
      ContentSigner contentSigner = (new JcaContentSignerBuilder(signatureAlgorithm)).build(signatureCredential.getPrivateKey());
      CMSAttributeTableGenerator cmsAttributeTableGenerator = (CMSAttributeTableGenerator)SignatureUtils.getOption("signedAttributeGenerator", optionMap, new DefaultSignedAttributeTableGenerator());
      signerInfoGeneratorBuilder.setSignedAttributeGenerator(cmsAttributeTableGenerator);
      generator.addSignerInfoGenerator(signerInfoGeneratorBuilder.build(contentSigner, signatureCredential.getCertificate()));
      Certificate[] certificateChain = signatureCredential.getCertificateChain();
      if (certificateChain != null && certificateChain.length > 0) {
         generator.addCertificates(new JcaCertStore(Arrays.asList(certificateChain)));
      }

      boolean encapsulate = (Boolean) SignatureUtils.getOption("encapsulate", optionMap, Boolean.FALSE);
      return generator.generate(content, encapsulate).getEncoded();
   } catch (Exception var14) {
      LOG.error(var14.getMessage(), var14);
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_SIGNATURE, var14, new Object[]{var14.getClass().getSimpleName() + " : " + var14.getMessage()});
   }
}
 
Example #15
Source File: CmsSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public byte[] sign(Credential signatureCredential, byte[] byteToSign, Map<String, Object> options) throws TechnicalConnectorException {
   byte[] contentToSign = ArrayUtils.clone(byteToSign);
   Map<String, Object> optionMap = new HashMap();
   if (options != null) {
      optionMap.putAll(options);
   }

   this.validateInput(signatureCredential, contentToSign);

   try {
      CMSTypedData content = new CMSProcessableByteArray(contentToSign);
      CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
      String signatureAlgorithm = (String)SignatureUtils.getOption("signatureAlgorithm", optionMap, "Sha1WithRSA");
      JcaSignerInfoGeneratorBuilder signerInfoGeneratorBuilder = new JcaSignerInfoGeneratorBuilder((new JcaDigestCalculatorProviderBuilder()).build());
      ContentSigner contentSigner = (new JcaContentSignerBuilder(signatureAlgorithm)).build(signatureCredential.getPrivateKey());
      CMSAttributeTableGenerator cmsAttributeTableGenerator = (CMSAttributeTableGenerator)SignatureUtils.getOption("signedAttributeGenerator", optionMap, new DefaultSignedAttributeTableGenerator());
      signerInfoGeneratorBuilder.setSignedAttributeGenerator(cmsAttributeTableGenerator);
      generator.addSignerInfoGenerator(signerInfoGeneratorBuilder.build(contentSigner, signatureCredential.getCertificate()));
      Certificate[] certificateChain = signatureCredential.getCertificateChain();
      if (certificateChain != null && certificateChain.length > 0) {
         generator.addCertificates(new JcaCertStore(Arrays.asList(certificateChain)));
      }

      boolean encapsulate = ((Boolean)SignatureUtils.getOption("encapsulate", optionMap, Boolean.FALSE)).booleanValue();
      return generator.generate(content, encapsulate).getEncoded();
   } catch (Exception var14) {
      LOG.error(var14.getMessage(), var14);
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_SIGNATURE, var14, new Object[]{var14.getClass().getSimpleName() + " : " + var14.getMessage()});
   }
}
 
Example #16
Source File: CmsSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public byte[] sign(Credential signatureCredential, byte[] byteToSign, Map<String, Object> options) throws TechnicalConnectorException {
   byte[] contentToSign = ArrayUtils.clone(byteToSign);
   Map<String, Object> optionMap = new HashMap();
   if (options != null) {
      optionMap.putAll(options);
   }

   this.validateInput(signatureCredential, contentToSign);

   try {
      CMSTypedData content = new CMSProcessableByteArray(contentToSign);
      CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
      String signatureAlgorithm = (String)SignatureUtils.getOption("signatureAlgorithm", optionMap, "Sha1WithRSA");
      JcaSignerInfoGeneratorBuilder signerInfoGeneratorBuilder = new JcaSignerInfoGeneratorBuilder((new JcaDigestCalculatorProviderBuilder()).build());
      ContentSigner contentSigner = (new JcaContentSignerBuilder(signatureAlgorithm)).build(signatureCredential.getPrivateKey());
      CMSAttributeTableGenerator cmsAttributeTableGenerator = (CMSAttributeTableGenerator)SignatureUtils.getOption("signedAttributeGenerator", optionMap, new DefaultSignedAttributeTableGenerator());
      signerInfoGeneratorBuilder.setSignedAttributeGenerator(cmsAttributeTableGenerator);
      generator.addSignerInfoGenerator(signerInfoGeneratorBuilder.build(contentSigner, signatureCredential.getCertificate()));
      Certificate[] certificateChain = signatureCredential.getCertificateChain();
      if (certificateChain != null && certificateChain.length > 0) {
         generator.addCertificates(new JcaCertStore(Arrays.asList(certificateChain)));
      }

      boolean encapsulate = ((Boolean)SignatureUtils.getOption("encapsulate", optionMap, Boolean.FALSE));
      return generator.generate(content, encapsulate).getEncoded();
   } catch (Exception var14) {
      LOG.error(var14.getMessage(), var14);
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_SIGNATURE, var14, new Object[]{var14.getClass().getSimpleName() + " : " + var14.getMessage()});
   }
}
 
Example #17
Source File: CmsSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public byte[] sign(Credential signatureCredential, byte[] byteToSign, Map<String, Object> options) throws TechnicalConnectorException {
   byte[] contentToSign = ArrayUtils.clone(byteToSign);
   Map<String, Object> optionMap = new HashMap();
   if (options != null) {
      optionMap.putAll(options);
   }

   this.validateInput(signatureCredential, contentToSign);

   try {
      CMSTypedData content = new CMSProcessableByteArray(contentToSign);
      CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
      String signatureAlgorithm = (String)SignatureUtils.getOption("signatureAlgorithm", optionMap, "Sha1WithRSA");
      JcaSignerInfoGeneratorBuilder signerInfoGeneratorBuilder = new JcaSignerInfoGeneratorBuilder((new JcaDigestCalculatorProviderBuilder()).build());
      ContentSigner contentSigner = (new JcaContentSignerBuilder(signatureAlgorithm)).build(signatureCredential.getPrivateKey());
      CMSAttributeTableGenerator cmsAttributeTableGenerator = (CMSAttributeTableGenerator)SignatureUtils.getOption("signedAttributeGenerator", optionMap, new DefaultSignedAttributeTableGenerator());
      signerInfoGeneratorBuilder.setSignedAttributeGenerator(cmsAttributeTableGenerator);
      generator.addSignerInfoGenerator(signerInfoGeneratorBuilder.build(contentSigner, signatureCredential.getCertificate()));
      Certificate[] certificateChain = signatureCredential.getCertificateChain();
      if (certificateChain != null && certificateChain.length > 0) {
         generator.addCertificates(new JcaCertStore(Arrays.asList(certificateChain)));
      }

      boolean encapsulate = (Boolean)SignatureUtils.getOption("encapsulate", optionMap, Boolean.FALSE);
      return generator.generate(content, encapsulate).getEncoded();
   } catch (Exception var14) {
      LOG.error(var14.getMessage(), var14);
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_SIGNATURE, var14, new Object[]{var14.getClass().getSimpleName() + " : " + var14.getMessage()});
   }
}
 
Example #18
Source File: RsaSsaPss.java    From testarea-itext5 with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * For some tests I needed SHA256withRSAandMGF1 CMS signatures.
 */
@Test
public void testCreateSimpleSignatureContainer() throws CMSException, GeneralSecurityException, OperatorCreationException, IOException
{
    byte[] message = "SHA256withRSAandMGF1".getBytes();
    CMSTypedData msg = new CMSProcessableByteArray(message);

    List<X509Certificate> certList = new ArrayList<X509Certificate>();
    certList.add(origCert);
    certList.add(signCert);
    Store certs = new JcaCertStore(certList);

    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA256withRSAandMGF1").setProvider("BC").build(signKP.getPrivate());

    gen.addSignerInfoGenerator(
              new JcaSignerInfoGeneratorBuilder(
                   new JcaDigestCalculatorProviderBuilder().setProvider("BC").build())
                   .build(sha1Signer, signCert));

    gen.addCertificates(certs);

    CMSSignedData sigData = gen.generate(msg, false);
    
    
    Files.write(new File(RESULT_FOLDER, "simpleMessageSHA256withRSAandMGF1.bin").toPath(), message);
    Files.write(new File(RESULT_FOLDER, "simpleMessageSHA256withRSAandMGF1.p7s").toPath(), sigData.getEncoded());
    
    boolean verifies = sigData.verifySignatures(new SignerInformationVerifierProvider()
    {
        @Override
        public SignerInformationVerifier get(SignerId sid) throws OperatorCreationException
        {
            if (sid.getSerialNumber().equals(origCert.getSerialNumber()))
            {
                System.out.println("SignerInformationVerifier requested for OrigCert");
                return new JcaSignerInfoVerifierBuilder(new BcDigestCalculatorProvider()).build(origCert);
            }
            if (sid.getSerialNumber().equals(signCert.getSerialNumber()))
            {
                System.out.println("SignerInformationVerifier requested for SignCert");
                return new JcaSignerInfoVerifierBuilder(new BcDigestCalculatorProvider()).build(signCert);
            }
            System.out.println("SignerInformationVerifier requested for unknown " + sid);
            return null;
        }
    });
    
    System.out.println("Verifies? " + verifies);
}
 
Example #19
Source File: OCSPCertificateVerifier.java    From oxAuth with MIT License 4 votes vote down vote up
@Override
public ValidationStatus validate(X509Certificate certificate, List<X509Certificate> issuers, Date validationDate) {
	X509Certificate issuer = issuers.get(0);
	ValidationStatus status = new ValidationStatus(certificate, issuer, validationDate, ValidatorSourceType.OCSP, CertificateValidity.UNKNOWN);

	try {
		Principal subjectX500Principal = certificate.getSubjectX500Principal();

		String ocspUrl = getOCSPUrl(certificate);
		if (ocspUrl == null) {
			log.error("OCSP URL for '" + subjectX500Principal + "' is empty");
			return status;
		}

		log.debug("OCSP URL for '" + subjectX500Principal + "' is '" + ocspUrl + "'");

		DigestCalculator digestCalculator = new JcaDigestCalculatorProviderBuilder().build().get(CertificateID.HASH_SHA1);
		CertificateID certificateId = new CertificateID(digestCalculator, new JcaX509CertificateHolder(certificate), certificate.getSerialNumber());

		// Generate OCSP request
		OCSPReq ocspReq = generateOCSPRequest(certificateId);

		// Get OCSP response from server
		OCSPResp ocspResp = requestOCSPResponse(ocspUrl, ocspReq);
		if (ocspResp.getStatus() != OCSPRespBuilder.SUCCESSFUL) {
			log.error("OCSP response is invalid!");
			status.setValidity(CertificateValidity.INVALID);
			return status;
		}

		boolean foundResponse = false;
		BasicOCSPResp basicOCSPResp = (BasicOCSPResp) ocspResp.getResponseObject();
		SingleResp[] singleResps = basicOCSPResp.getResponses();
		for (SingleResp singleResp : singleResps) {
			CertificateID responseCertificateId = singleResp.getCertID();
			if (!certificateId.equals(responseCertificateId)) {
				continue;
			}

			foundResponse = true;

			log.debug("OCSP validationDate: " + validationDate);
			log.debug("OCSP thisUpdate: " + singleResp.getThisUpdate());
			log.debug("OCSP nextUpdate: " + singleResp.getNextUpdate());

			status.setRevocationObjectIssuingTime(basicOCSPResp.getProducedAt());

			Object certStatus = singleResp.getCertStatus();
			if (certStatus == CertificateStatus.GOOD) {
				log.debug("OCSP status is valid for '" + certificate.getSubjectX500Principal() + "'");
				status.setValidity(CertificateValidity.VALID);
			} else {
				if (singleResp.getCertStatus() instanceof RevokedStatus) {
					log.warn("OCSP status is revoked for: " + subjectX500Principal);
					if (validationDate.before(((RevokedStatus) singleResp.getCertStatus()).getRevocationTime())) {
						log.warn("OCSP revocation time after the validation date, the certificate '" + subjectX500Principal + "' was valid at " + validationDate);
						status.setValidity(CertificateValidity.VALID);
					} else {
						Date revocationDate = ((RevokedStatus) singleResp.getCertStatus()).getRevocationTime();
						log.info("OCSP for certificate '" + subjectX500Principal + "' is revoked since " + revocationDate);
						status.setRevocationDate(revocationDate);
						status.setRevocationObjectIssuingTime(singleResp.getThisUpdate());
						status.setValidity(CertificateValidity.REVOKED);
					}
				}
			}
		}

		if (!foundResponse) {
			log.error("There is no matching OCSP response entries");
		}
	} catch (Exception ex) {
		log.error("OCSP exception: ", ex);
	}

	return status;
}
 
Example #20
Source File: OcspHandler.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    if (exchange.isInIoThread()) {
        exchange.dispatch(this);
        return;
    }

    final byte[] buffy = new byte[16384];
    try (InputStream requestStream = exchange.getInputStream()) {
        requestStream.read(buffy);
    }

    final OCSPReq request = new OCSPReq(buffy);
    final Req[] requested = request.getRequestList();

    final Extension nonce = request.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);

    final DigestCalculator sha1Calculator = new JcaDigestCalculatorProviderBuilder().build()
            .get(AlgorithmIdentifier.getInstance(RespID.HASH_SHA1));

    final BasicOCSPRespBuilder responseBuilder = new BasicOCSPRespBuilder(subjectPublicKeyInfo, sha1Calculator);

    if (nonce != null) {
        responseBuilder.setResponseExtensions(new Extensions(nonce));
    }

    for (final Req req : requested) {
        final CertificateID certId = req.getCertID();

        final BigInteger certificateSerialNumber = certId.getSerialNumber();
        responseBuilder.addResponse(certId, REVOKED_CERTIFICATES_STATUS.get(certificateSerialNumber));
    }

    final ContentSigner contentSigner = new BcRSAContentSignerBuilder(
            new AlgorithmIdentifier(PKCSObjectIdentifiers.sha256WithRSAEncryption),
            new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256)).build(privateKey);

    final OCSPResp response = new OCSPRespBuilder().build(OCSPResp.SUCCESSFUL,
            responseBuilder.build(contentSigner, chain, new Date()));

    final byte[] responseBytes = response.getEncoded();

    final HeaderMap responseHeaders = exchange.getResponseHeaders();
    responseHeaders.put(Headers.CONTENT_TYPE, "application/ocsp-response");

    final Sender responseSender = exchange.getResponseSender();
    responseSender.send(ByteBuffer.wrap(responseBytes));

    exchange.endExchange();
}