org.bouncycastle.operator.bc.BcDigestCalculatorProvider Java Examples

The following examples show how to use org.bouncycastle.operator.bc.BcDigestCalculatorProvider. 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: CAdESSignature.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * This method recreates a {@code SignerInformation} with the content using
 * a {@code CMSSignedDataParser}.
 *
 * @return
 * @throws CMSException
 * @throws IOException
 */
private SignerInformation recreateSignerInformation() throws CMSException, IOException {

	final DSSDocument dssDocument = detachedContents.get(0); // only one element for CAdES Signature
	CMSSignedDataParser cmsSignedDataParser = null;
	if (dssDocument instanceof DigestDocument) {
		cmsSignedDataParser = new CMSSignedDataParser(new PrecomputedDigestCalculatorProvider((DigestDocument) dssDocument), cmsSignedData.getEncoded());
	} else {
		try (InputStream inputStream = dssDocument.openStream()) {
			final CMSTypedStream signedContent = new CMSTypedStream(inputStream);
			cmsSignedDataParser = new CMSSignedDataParser(new BcDigestCalculatorProvider(), signedContent, cmsSignedData.getEncoded());
			cmsSignedDataParser.getSignedContent().drain(); // Closes the stream
		}
	}

	final SignerId signerId = getSignerId();
	final SignerInformation signerInformationToCheck = cmsSignedDataParser.getSignerInfos().get(signerId);
	return signerInformationToCheck;
}
 
Example #2
Source File: TimeStampValidatorImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public void validateTimeStampToken(TimeStampToken tsToken) throws InvalidTimeStampException, TechnicalConnectorException {
   Validate.notNull(this.keyStore, "keyStore is not correctly initialised.");
   Validate.notNull(this.aliases, "aliases is not correctly initialised.");
   Validate.notNull(tsToken, "Parameter tsToken value is not nullable.");
   TimeStampTokenInfo timeStampInfo = tsToken.getTimeStampInfo();
   if (timeStampInfo != null) {
      LOG.debug("Validating TimeStampToken with SerialNumber [" + timeStampInfo.getSerialNumber() + "]");
      if (timeStampInfo.getTsa() != null) {
         X500Name name = (X500Name)timeStampInfo.getTsa().getName();
         LOG.debug("Validating Timestamp against TrustStore Looking for [" + name + "].");
      }
   }

   boolean signatureValid = false;
   Exception lastException = null;
   Iterator i$ = this.aliases.iterator();

   while(i$.hasNext()) {
      String alias = (String)i$.next();

      try {
         X509Certificate ttsaCert = (X509Certificate)this.keyStore.getCertificate(alias);
         LOG.debug("Trying to validate timestamp against certificate with alias [" + alias + "] : [" + ttsaCert.getSubjectX500Principal().getName("RFC1779") + "]");
         X509CertificateHolder tokenSigner = new X509CertificateHolder(ttsaCert.getEncoded());
         SignerInformationVerifier verifier = (new BcRSASignerInfoVerifierBuilder(new DefaultCMSSignatureAlgorithmNameGenerator(), new DefaultSignatureAlgorithmIdentifierFinder(), new DefaultDigestAlgorithmIdentifierFinder(), new BcDigestCalculatorProvider())).build(tokenSigner);
         tsToken.validate(verifier);
         signatureValid = true;
         break;
      } catch (Exception var10) {
         lastException = var10;
         LOG.debug("TimeStampToken not valid with certificate-alias [" + alias + "]: " + var10.getMessage());
      }
   }

   if (!signatureValid) {
      throw new InvalidTimeStampException("timestamp is not valid ", lastException);
   } else {
      LOG.debug("timestampToken is valid");
   }
}
 
Example #3
Source File: TimeStampValidatorImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public void validateTimeStampToken(TimeStampToken tsToken) throws InvalidTimeStampException, TechnicalConnectorException {
   Validate.notNull(this.keyStore, "keyStore is not correctly initialised.");
   Validate.notNull(this.aliases, "aliases is not correctly initialised.");
   Validate.notNull(tsToken, "Parameter tsToken value is not nullable.");
   if (tsToken.getTimeStampInfo() != null) {
      LOG.debug("Validating TimeStampToken with SerialNumber [" + tsToken.getTimeStampInfo().getSerialNumber() + "]");
   }

   boolean signatureValid = false;
   Exception lastException = null;
   Iterator i$ = this.aliases.iterator();

   while(i$.hasNext()) {
      String alias = (String)i$.next();

      try {
         X509Certificate ttsaCert = (X509Certificate)this.keyStore.getCertificate(alias);
         LOG.debug("Trying to validate timestamp against certificate with alias [" + alias + "] : [" + ttsaCert.getSubjectX500Principal().getName("RFC1779") + "]");
         X509CertificateHolder tokenSigner = new X509CertificateHolder(ttsaCert.getEncoded());
         SignerInformationVerifier verifier = (new BcRSASignerInfoVerifierBuilder(new DefaultCMSSignatureAlgorithmNameGenerator(), new DefaultSignatureAlgorithmIdentifierFinder(), new DefaultDigestAlgorithmIdentifierFinder(), new BcDigestCalculatorProvider())).build(tokenSigner);
         tsToken.validate(verifier);
         signatureValid = true;
         break;
      } catch (Exception var9) {
         lastException = var9;
         LOG.debug("TimeStampToken not valid with certificate-alias [" + alias + "]: " + var9.getMessage());
      }
   }

   if (!signatureValid) {
      throw new InvalidTimeStampException("timestamp is not valid ", lastException);
   } else {
      LOG.debug("timestampToken is valid");
   }
}
 
Example #4
Source File: TimeStampValidatorImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public void validateTimeStampToken(TimeStampToken tsToken) throws InvalidTimeStampException, TechnicalConnectorException {
   Validate.notNull(this.keyStore, "keyStore is not correctly initialised.");
   Validate.notNull(this.aliases, "aliases is not correctly initialised.");
   Validate.notNull(tsToken, "Parameter tsToken value is not nullable.");
   if (tsToken.getTimeStampInfo() != null) {
      LOG.debug("Validating TimeStampToken with SerialNumber [" + tsToken.getTimeStampInfo().getSerialNumber() + "]");
   }

   boolean signatureValid = false;
   Exception lastException = null;
   Iterator i$ = this.aliases.iterator();

   while(i$.hasNext()) {
      String alias = (String)i$.next();

      try {
         X509Certificate ttsaCert = (X509Certificate)this.keyStore.getCertificate(alias);
         LOG.debug("Trying to validate timestamp against certificate with alias [" + alias + "] : [" + ttsaCert.getSubjectX500Principal().getName("RFC1779") + "]");
         X509CertificateHolder tokenSigner = new X509CertificateHolder(ttsaCert.getEncoded());
         SignerInformationVerifier verifier = (new BcRSASignerInfoVerifierBuilder(new DefaultCMSSignatureAlgorithmNameGenerator(), new DefaultSignatureAlgorithmIdentifierFinder(), new DefaultDigestAlgorithmIdentifierFinder(), new BcDigestCalculatorProvider())).build(tokenSigner);
         tsToken.validate(verifier);
         signatureValid = true;
         break;
      } catch (Exception var9) {
         lastException = var9;
         LOG.debug("TimeStampToken not valid with certificate-alias [" + alias + "]: " + var9.getMessage());
      }
   }

   if (!signatureValid) {
      throw new InvalidTimeStampException("timestamp is not valid ", lastException);
   } else {
      LOG.debug("timestampToken is valid");
   }
}
 
Example #5
Source File: TimeStampValidatorImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public void validateTimeStampToken(TimeStampToken tsToken) throws InvalidTimeStampException, TechnicalConnectorException {
   Validate.notNull(this.keyStore, "keyStore is not correctly initialised.");
   Validate.notNull(this.aliases, "aliases is not correctly initialised.");
   Validate.notNull(tsToken, "Parameter tsToken value is not nullable.");
   TimeStampTokenInfo timeStampInfo = tsToken.getTimeStampInfo();
   if (timeStampInfo != null) {
      LOG.debug("Validating TimeStampToken with SerialNumber [" + timeStampInfo.getSerialNumber() + "]");
      if (timeStampInfo.getTsa() != null) {
         X500Name name = (X500Name)timeStampInfo.getTsa().getName();
         LOG.debug("Validating Timestamp against TrustStore Looking for [" + name + "].");
      }
   }

   boolean signatureValid = false;
   Exception lastException = null;
   Iterator i$ = this.aliases.iterator();

   while(i$.hasNext()) {
      String alias = (String)i$.next();

      try {
         X509Certificate ttsaCert = (X509Certificate)this.keyStore.getCertificate(alias);
         LOG.debug("Trying to validate timestamp against certificate with alias [" + alias + "] : [" + ttsaCert.getSubjectX500Principal().getName("RFC1779") + "]");
         X509CertificateHolder tokenSigner = new X509CertificateHolder(ttsaCert.getEncoded());
         SignerInformationVerifier verifier = (new BcRSASignerInfoVerifierBuilder(new DefaultCMSSignatureAlgorithmNameGenerator(), new DefaultSignatureAlgorithmIdentifierFinder(), new DefaultDigestAlgorithmIdentifierFinder(), new BcDigestCalculatorProvider())).build(tokenSigner);
         tsToken.validate(verifier);
         signatureValid = true;
         break;
      } catch (Exception var10) {
         lastException = var10;
         LOG.debug("TimeStampToken not valid with certificate-alias [" + alias + "]: " + var10.getMessage());
      }
   }

   if (!signatureValid) {
      throw new InvalidTimeStampException("timestamp is not valid ", lastException);
   } else {
      LOG.debug("timestampToken is valid");
   }
}
 
Example #6
Source File: CAdESService.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private DigestCalculatorProvider getDigestCalculatorProvider(DSSDocument toSignDocument, CAdESSignatureParameters parameters) {
	DigestAlgorithm referenceDigestAlgorithm = parameters.getReferenceDigestAlgorithm();
	if (referenceDigestAlgorithm != null) {
		return new CustomMessageDigestCalculatorProvider(referenceDigestAlgorithm, toSignDocument.getDigest(referenceDigestAlgorithm));
	} else if (toSignDocument instanceof DigestDocument) {
		return new PrecomputedDigestCalculatorProvider((DigestDocument) toSignDocument);
	}
	return new BcDigestCalculatorProvider();
}
 
Example #7
Source File: DeviceCertificateManager.java    From enmasse with Apache License 2.0 5 votes vote down vote up
private static AuthorityKeyIdentifier createAuthorityKeyId(final PublicKey publicKey)
        throws OperatorCreationException {

    final SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
    final DigestCalculator digCalc = new BcDigestCalculatorProvider()
            .get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));

    return new X509ExtensionUtils(digCalc)
            .createAuthorityKeyIdentifier(publicKeyInfo);

}
 
Example #8
Source File: CertificateUtils.java    From keycloak with Apache License 2.0 4 votes vote down vote up
/**
 * Generates version 3 {@link java.security.cert.X509Certificate}.
 *
 * @param keyPair the key pair
 * @param caPrivateKey the CA private key
 * @param caCert the CA certificate
 * @param subject the subject name
 * 
 * @return the x509 certificate
 * 
 * @throws Exception the exception
 */
public static X509Certificate generateV3Certificate(KeyPair keyPair, PrivateKey caPrivateKey, X509Certificate caCert,
        String subject) throws Exception {
    try {
        X500Name subjectDN = new X500Name("CN=" + subject);

        // Serial Number
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        BigInteger serialNumber = BigInteger.valueOf(Math.abs(random.nextInt()));

        // Validity
        Date notBefore = new Date(System.currentTimeMillis());
        Date notAfter = new Date(System.currentTimeMillis() + (((1000L * 60 * 60 * 24 * 30)) * 12) * 3);

        // SubjectPublicKeyInfo
        SubjectPublicKeyInfo subjPubKeyInfo = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(keyPair.getPublic()
                .getEncoded()));

        X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(new X500Name(caCert.getSubjectDN().getName()),
                serialNumber, notBefore, notAfter, subjectDN, subjPubKeyInfo);

        DigestCalculator digCalc = new BcDigestCalculatorProvider()
                .get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));
        X509ExtensionUtils x509ExtensionUtils = new X509ExtensionUtils(digCalc);

        // Subject Key Identifier
        certGen.addExtension(Extension.subjectKeyIdentifier, false,
                x509ExtensionUtils.createSubjectKeyIdentifier(subjPubKeyInfo));

        // Authority Key Identifier
        certGen.addExtension(Extension.authorityKeyIdentifier, false,
                x509ExtensionUtils.createAuthorityKeyIdentifier(subjPubKeyInfo));

        // Key Usage
        certGen.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign
                | KeyUsage.cRLSign));

        // Extended Key Usage
        KeyPurposeId[] EKU = new KeyPurposeId[2];
        EKU[0] = KeyPurposeId.id_kp_emailProtection;
        EKU[1] = KeyPurposeId.id_kp_serverAuth;

        certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(EKU));

        // Basic Constraints
        certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(0));

        // Content Signer
        ContentSigner sigGen = new JcaContentSignerBuilder("SHA1WithRSAEncryption").setProvider("BC").build(caPrivateKey);

        // Certificate
        return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen));
    } catch (Exception e) {
        throw new RuntimeException("Error creating X509v3Certificate.", e);
    }
}
 
Example #9
Source File: CertificateRequest.java    From jqm with Apache License 2.0 4 votes vote down vote up
private void generateX509() throws Exception
{
    SecureRandom random = new SecureRandom();
    X500Name dnName = new X500Name(Subject);
    Calendar endValidity = Calendar.getInstance();
    endValidity.add(Calendar.YEAR, validityYear);

    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());

    X509v3CertificateBuilder gen = new X509v3CertificateBuilder(
            authorityCertificate == null ? dnName : authorityCertificate.getSubject(),
            BigIntegers.createRandomInRange(BigInteger.ZERO, BigInteger.valueOf(Long.MAX_VALUE), random), new Date(),
            endValidity.getTime(), dnName, publicKeyInfo);

    // Public key ID
    DigestCalculator digCalc = new BcDigestCalculatorProvider().get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));
    X509ExtensionUtils x509ExtensionUtils = new X509ExtensionUtils(digCalc);
    gen.addExtension(Extension.subjectKeyIdentifier, false, x509ExtensionUtils.createSubjectKeyIdentifier(publicKeyInfo));

    // EKU
    gen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(EKU));

    // Basic constraints (is CA?)
    if (authorityCertificate == null)
    {
        gen.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
    }

    // Key usage
    gen.addExtension(Extension.keyUsage, true, new KeyUsage(keyUsage));

    // Subject Alt names ?

    // Authority
    if (authorityCertificate != null)
    {
        gen.addExtension(Extension.authorityKeyIdentifier, false,
                new AuthorityKeyIdentifier(authorityCertificate.getSubjectPublicKeyInfo()));
    }

    // Signer
    ContentSigner signer = new JcaContentSignerBuilder("SHA512WithRSAEncryption").setProvider(Constants.JCA_PROVIDER)
            .build(authorityKey == null ? privateKey : authorityKey);

    // Go
    holder = gen.build(signer);
}
 
Example #10
Source File: NextCaMessage.java    From xipki with Apache License 2.0 4 votes vote down vote up
public ContentInfo encode(PrivateKey signingKey, X509Cert signerCert,
    X509Cert[] cmsCertSet) throws MessageEncodingException {
  Args.notNull(signingKey, "signingKey");
  Args.notNull(signerCert, "signerCert");

  try {
    CMSSignedDataGenerator degenerateSignedData = new CMSSignedDataGenerator();
    degenerateSignedData.addCertificate(caCert.toBcCert());
    if (CollectionUtil.isNotEmpty(raCerts)) {
      for (X509Cert m : raCerts) {
        degenerateSignedData.addCertificate(m.toBcCert());
      }
    }

    byte[] degenratedSignedDataBytes = degenerateSignedData.generate(
        new CMSAbsentContent()).getEncoded();

    CMSSignedDataGenerator generator = new CMSSignedDataGenerator();

    // I don't known which hash algorithm is supported by the client, use SHA-1
    String signatureAlgo = getSignatureAlgorithm(signingKey, HashAlgo.SHA1);
    ContentSigner signer = new JcaContentSignerBuilder(signatureAlgo).build(signingKey);

    // signerInfo
    JcaSignerInfoGeneratorBuilder signerInfoBuilder = new JcaSignerInfoGeneratorBuilder(
        new BcDigestCalculatorProvider());

    signerInfoBuilder.setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator());

    SignerInfoGenerator signerInfo = signerInfoBuilder.build(signer, signerCert.toBcCert());
    generator.addSignerInfoGenerator(signerInfo);

    CMSTypedData cmsContent = new CMSProcessableByteArray(CMSObjectIdentifiers.signedData,
        degenratedSignedDataBytes);

    // certificateSet
    ScepUtil.addCmsCertSet(generator, cmsCertSet);
    return generator.generate(cmsContent, true).toASN1Structure();
  } catch (CMSException | CertificateEncodingException | IOException
      | OperatorCreationException ex) {
    throw new MessageEncodingException(ex);
  }
}
 
Example #11
Source File: CreateSignature.java    From testarea-pdfbox2 with Apache License 2.0 4 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/41767351/create-pkcs7-signature-from-file-digest">
 * Create pkcs7 signature from file digest
 * </a>
 * <p>
 * The OP's <code>sign</code> method after fixing some errors. The
 * OP's original method is {@link #signBySnox(InputStream)}. The
 * errors were
 * </p>
 * <ul>
 * <li>multiple attempts at reading the {@link InputStream} parameter;
 * <li>convoluted creation of final CMS container.
 * </ul>
 * <p>
 * Additionally this method uses SHA256 instead of SHA-1.
 * </p>
 */
public byte[] signWithSeparatedHashing(InputStream content) throws IOException
{
    try
    {
        // Digest generation step
        MessageDigest md = MessageDigest.getInstance("SHA256", "BC");
        byte[] digest = md.digest(IOUtils.toByteArray(content));

        // Separate signature container creation step
        List<Certificate> certList = Arrays.asList(chain);
        JcaCertStore certs = new JcaCertStore(certList);

        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();

        Attribute attr = new Attribute(CMSAttributes.messageDigest,
                new DERSet(new DEROctetString(digest)));

        ASN1EncodableVector v = new ASN1EncodableVector();

        v.add(attr);

        SignerInfoGeneratorBuilder builder = new SignerInfoGeneratorBuilder(new BcDigestCalculatorProvider())
                .setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(new AttributeTable(v)));

        AlgorithmIdentifier sha256withRSA = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA");

        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
        InputStream in = new ByteArrayInputStream(chain[0].getEncoded());
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in);

        gen.addSignerInfoGenerator(builder.build(
                new BcRSAContentSignerBuilder(sha256withRSA,
                        new DefaultDigestAlgorithmIdentifierFinder().find(sha256withRSA))
                                .build(PrivateKeyFactory.createKey(pk.getEncoded())),
                new JcaX509CertificateHolder(cert)));

        gen.addCertificates(certs);

        CMSSignedData s = gen.generate(new CMSAbsentContent(), false);
        return s.getEncoded();
    }
    catch (Exception e)
    {
        e.printStackTrace();
        throw new IOException(e);
    }
}
 
Example #12
Source File: CreateSignature.java    From testarea-pdfbox2 with Apache License 2.0 4 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/41767351/create-pkcs7-signature-from-file-digest">
 * Create pkcs7 signature from file digest
 * </a>
 * <p>
 * The OP's own <code>sign</code> method which has some errors. These
 * errors are fixed in {@link #signWithSeparatedHashing(InputStream)}.
 * </p>
 */
public byte[] signBySnox(InputStream content) throws IOException {
    // testSHA1WithRSAAndAttributeTable
    try {
        MessageDigest md = MessageDigest.getInstance("SHA1", "BC");
        List<Certificate> certList = new ArrayList<Certificate>();
        CMSTypedData msg = new CMSProcessableByteArray(IOUtils.toByteArray(content));

        certList.addAll(Arrays.asList(chain));

        Store<?> certs = new JcaCertStore(certList);

        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();

        Attribute attr = new Attribute(CMSAttributes.messageDigest,
                new DERSet(new DEROctetString(md.digest(IOUtils.toByteArray(content)))));

        ASN1EncodableVector v = new ASN1EncodableVector();

        v.add(attr);

        SignerInfoGeneratorBuilder builder = new SignerInfoGeneratorBuilder(new BcDigestCalculatorProvider())
                .setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(new AttributeTable(v)));

        AlgorithmIdentifier sha1withRSA = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA");

        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
        InputStream in = new ByteArrayInputStream(chain[0].getEncoded());
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in);

        gen.addSignerInfoGenerator(builder.build(
                new BcRSAContentSignerBuilder(sha1withRSA,
                        new DefaultDigestAlgorithmIdentifierFinder().find(sha1withRSA))
                                .build(PrivateKeyFactory.createKey(pk.getEncoded())),
                new JcaX509CertificateHolder(cert)));

        gen.addCertificates(certs);

        CMSSignedData s = gen.generate(new CMSAbsentContent(), false);
        return new CMSSignedData(msg, s.getEncoded()).getEncoded();

    } catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e);
    }
}
 
Example #13
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 #14
Source File: AbstractIntegrationModule.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
private boolean validateTimeStampToken(TimeStampToken tsToken) throws Exception {
    boolean result = false;
    KeyStore keyStore = getEncryptionUtils().getTSAKeyStore();
    List<String> aliases = getEncryptionUtils().getTsaStoreAliases();
    if (aliases == null || keyStore == null) {
        throw new IllegalStateException("keystore or aliases not initialised yet : aliases : [" + aliases + "] and keystore : [" + keyStore + "]");
    }

    TimeStampTokenInfo tsi = tsToken.getTimeStampInfo();

    LOG.info("GenTime:" + tsi.getGenTime());
    LOG.info("ImprintAlgOID:" + tsi.getMessageImprintAlgOID());
    LOG.info("Policy:" + tsi.getPolicy());
    //LOG.info("Accuracy:" + tsi.getAccuracy().getSeconds());
    LOG.info("HashAlgorithm:" + tsi.getHashAlgorithm().getAlgorithm().getId());

    boolean signatureValid = false;

    Exception lastException = null;
    for (String alias : aliases) {
        try {
            X509Certificate ttsaCert = (X509Certificate) keyStore.getCertificate(alias);
            String t = ttsaCert.getSubjectX500Principal().getName(X500Principal.RFC1779);
            LOG.debug("Trying to validate timestamp against certificate with alias [" + alias + "] : [" + t + "]");

            X509CertificateHolder tokenSigner = new X509CertificateHolder(ttsaCert.getEncoded());
            SignerInformationVerifier verifier = new BcRSASignerInfoVerifierBuilder(new DefaultCMSSignatureAlgorithmNameGenerator(),
                    new DefaultSignatureAlgorithmIdentifierFinder(), new DefaultDigestAlgorithmIdentifierFinder(), new BcDigestCalculatorProvider()).build(
                    tokenSigner);
            tsToken.validate(verifier);
            signatureValid = true;
            break;
        } catch (Exception e) {
            lastException = e;
            //throw new Exception("timestamp not valid with certificate-alias '" + alias + "': " + e.getMessage());
        }
    }
    if (signatureValid) {
        result = true;
        LOG.debug("timestampToken is valid");
    } else {
        result = false;
        throw new Exception("timestamp is not valid ", lastException);
    }
    return result;
}
 
Example #15
Source File: AbstractIntegrationModule.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
private boolean validateTimeStampToken(TimeStampToken tsToken) throws Exception {
   boolean result = false;
   KeyStore keyStore = this.getEncryptionUtils().getTSAKeyStore();
   List<String> aliases = this.getEncryptionUtils().getTsaStoreAliases();
   if (aliases != null && keyStore != null) {
      TimeStampTokenInfo tsi = tsToken.getTimeStampInfo();
      LOG.info("GenTime:" + tsi.getGenTime());
      LOG.info("ImprintAlgOID:" + tsi.getMessageImprintAlgOID());
      LOG.info("Policy:" + tsi.getPolicy());
      LOG.info("HashAlgorithm:" + tsi.getHashAlgorithm().getAlgorithm().getId());
      boolean signatureValid = false;
      Exception lastException = null;
      Iterator var9 = aliases.iterator();

      while(var9.hasNext()) {
         String alias = (String)var9.next();

         try {
            X509Certificate ttsaCert = (X509Certificate)keyStore.getCertificate(alias);
            String t = ttsaCert.getSubjectX500Principal().getName("RFC1779");
            LOG.debug("Trying to validate timestamp against certificate with alias [" + alias + "] : [" + t + "]");
            X509CertificateHolder tokenSigner = new X509CertificateHolder(ttsaCert.getEncoded());
            SignerInformationVerifier verifier = (new BcRSASignerInfoVerifierBuilder(new DefaultCMSSignatureAlgorithmNameGenerator(), new DefaultSignatureAlgorithmIdentifierFinder(), new DefaultDigestAlgorithmIdentifierFinder(), new BcDigestCalculatorProvider())).build(tokenSigner);
            tsToken.validate(verifier);
            signatureValid = true;
            break;
         } catch (Exception var14) {
            lastException = var14;
         }
      }

      if (signatureValid) {
         result = true;
         LOG.debug("timestampToken is valid");
         return result;
      } else {
         result = false;
         throw new Exception("timestamp is not valid ", lastException);
      }
   } else {
      throw new IllegalStateException("keystore or aliases not initialised yet : aliases : [" + aliases + "] and keystore : [" + keyStore + "]");
   }
}
 
Example #16
Source File: AbstractIntegrationModule.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
private boolean validateTimeStampToken(TimeStampToken tsToken) throws Exception {
    boolean result = false;
    KeyStore keyStore = getEncryptionUtils().getTSAKeyStore();
    List<String> aliases = getEncryptionUtils().getTsaStoreAliases();
    if (aliases == null || keyStore == null) {
        throw new IllegalStateException("keystore or aliases not initialised yet : aliases : [" + aliases + "] and keystore : [" + keyStore + "]");
    }

    TimeStampTokenInfo tsi = tsToken.getTimeStampInfo();

    LOG.info("GenTime:" + tsi.getGenTime());
    LOG.info("ImprintAlgOID:" + tsi.getMessageImprintAlgOID());
    LOG.info("Policy:" + tsi.getPolicy());
    //LOG.info("Accuracy:" + tsi.getAccuracy().getSeconds());
    LOG.info("HashAlgorithm:" + tsi.getHashAlgorithm().getAlgorithm().getId());

    boolean signatureValid = false;

    Exception lastException = null;
    for (String alias : aliases) {
        try {
            X509Certificate ttsaCert = (X509Certificate) keyStore.getCertificate(alias);
            String t = ttsaCert.getSubjectX500Principal().getName(X500Principal.RFC1779);
            LOG.debug("Trying to validate timestamp against certificate with alias [" + alias + "] : [" + t + "]");

            X509CertificateHolder tokenSigner = new X509CertificateHolder(ttsaCert.getEncoded());
            SignerInformationVerifier verifier = new BcRSASignerInfoVerifierBuilder(new DefaultCMSSignatureAlgorithmNameGenerator(),
                    new DefaultSignatureAlgorithmIdentifierFinder(), new DefaultDigestAlgorithmIdentifierFinder(), new BcDigestCalculatorProvider()).build(
                    tokenSigner);
            tsToken.validate(verifier);
            signatureValid = true;
            break;
        } catch (Exception e) {
            lastException = e;
            //throw new Exception("timestamp not valid with certificate-alias '" + alias + "': " + e.getMessage());
        }
    }
    if (signatureValid) {
        result = true;
        LOG.debug("timestampToken is valid");
    } else {
        result = false;
        throw new Exception("timestamp is not valid ", lastException);
    }
    return result;
}
 
Example #17
Source File: DeviceCertificateManager.java    From enmasse with Apache License 2.0 3 votes vote down vote up
private static SubjectKeyIdentifier createSubjectKeyId(final PublicKey publicKey) throws OperatorCreationException {

        final SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
        final DigestCalculator digCalc = new BcDigestCalculatorProvider()
                .get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));

        return new X509ExtensionUtils(digCalc)
                .createSubjectKeyIdentifier(publicKeyInfo);

    }