org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder Java Examples

The following examples show how to use org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder. 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: TestSSLUtils.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Create a self-signed X.509 Certificate.
 * From http://bfo.com/blog/2011/03/08/odds_and_ends_creating_a_new_x_509_certificate.html.
 *
 * @param dn the X.509 Distinguished Name, eg "CN(commonName)=Test, O(organizationName)=Org"
 * @param pair the KeyPair
 * @param days how many days from now the Certificate is valid for
 * @param algorithm the signing algorithm, eg "SHA1withRSA"
 * @return the self-signed certificate
 * @throws java.security.cert.CertificateException thrown if a security error or an IO error ocurred.
 */
public static X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm)
    throws CertificateException {
  try {
    Security.addProvider(new BouncyCastleProvider());
    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm);
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(pair.getPrivate().getEncoded());
    SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded());
    ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);
    X500Name name = new X500Name(dn);
    Date from = new Date();
    Date to = new Date(from.getTime() + days * 86400000L);
    BigInteger sn = new BigInteger(64, new SecureRandom());

    X509v1CertificateBuilder v1CertGen = new X509v1CertificateBuilder(name, sn, from, to, name, subPubKeyInfo);
    X509CertificateHolder certificateHolder = v1CertGen.build(sigGen);
    return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
  } catch (CertificateException ce) {
    throw ce;
  } catch (Exception e) {
    throw new CertificateException(e);
  }
}
 
Example #2
Source File: TestSslUtils.java    From li-apache-kafka-clients with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Create a self-signed X.509 Certificate.
 * From http://bfo.com/blog/2011/03/08/odds_and_ends_creating_a_new_x_509_certificate.html.
 *
 * @param dn        the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB"
 * @param pair      the KeyPair
 * @param days      how many days from now the Certificate is valid for
 * @param algorithm the signing algorithm, eg "SHA1withRSA"
 * @return the self-signed certificate
 * @throws CertificateException thrown if a security error or an IO error occurred.
 */
public static X509Certificate generateCertificate(String dn, KeyPair pair,
                                                  int days, String algorithm)
    throws CertificateException {

  try {
    Security.addProvider(new BouncyCastleProvider());
    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm);
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(pair.getPrivate().getEncoded());
    SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded());
    ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);
    X500Name name = new X500Name(dn);
    Date from = new Date();
    Date to = new Date(from.getTime() + days * 86400000L);
    BigInteger sn = new BigInteger(64, new SecureRandom());

    X509v1CertificateBuilder v1CertGen = new X509v1CertificateBuilder(name, sn, from, to, name, subPubKeyInfo);
    X509CertificateHolder certificateHolder = v1CertGen.build(sigGen);
    return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
  } catch (CertificateException ce) {
    throw ce;
  } catch (Exception e) {
    throw new CertificateException(e);
  }
}
 
Example #3
Source File: CertificateManager.java    From Launcher with GNU General Public License v3.0 6 votes vote down vote up
public X509CertificateHolder generateCertificate(String subjectName, PublicKey subjectPublicKey) throws OperatorCreationException {
    SubjectPublicKeyInfo subjectPubKeyInfo = SubjectPublicKeyInfo.getInstance(subjectPublicKey.getEncoded());
    BigInteger serial = BigInteger.valueOf(SecurityHelper.newRandom().nextLong());
    Date startDate = Date.from(Instant.now().minus(minusHours, ChronoUnit.HOURS));
    Date endDate = Date.from(startDate.toInstant().plus(validDays, ChronoUnit.DAYS));

    X500NameBuilder subject = new X500NameBuilder();
    subject.addRDN(BCStyle.CN, subjectName);
    subject.addRDN(BCStyle.O, orgName);
    X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(ca.getSubject(), serial,
            startDate, endDate, subject.build(), subjectPubKeyInfo);

    AlgorithmIdentifier sigAlgId = ca.getSignatureAlgorithm();
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    ContentSigner sigGen = new BcECContentSignerBuilder(sigAlgId, digAlgId).build(caKey);

    return v3CertGen.build(sigGen);
}
 
Example #4
Source File: SSLKeyPairCerts.java    From vertx-tcp-eventbus-bridge with Apache License 2.0 6 votes vote down vote up
private X509Certificate generateSelfSignedCert(String certSub, KeyPair keyPair) throws Exception {
  final X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(
    new org.bouncycastle.asn1.x500.X500Name(certSub),
    BigInteger.ONE,
    new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30),
    new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)),
    new X500Name(certSub),
    SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded())
  );
  final GeneralNames subjectAltNames = new GeneralNames(new GeneralName(GeneralName.iPAddress, "127.0.0.1"));
  certificateBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.subjectAlternativeName, false, subjectAltNames);

  final AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1WithRSAEncryption");
  final AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
  final BcContentSignerBuilder signerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId);
  final AsymmetricKeyParameter keyp = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded());
  final ContentSigner signer = signerBuilder.build(keyp);
  final X509CertificateHolder x509CertificateHolder = certificateBuilder.build(signer);
  final X509Certificate certificate = new JcaX509CertificateConverter().getCertificate(x509CertificateHolder);
  certificate.checkValidity(new Date());
  certificate.verify(keyPair.getPublic());
  return certificate;
}
 
Example #5
Source File: FTPAndSSHDUnitTest.java    From datacollector with Apache License 2.0 6 votes vote down vote up
private X509Certificate generateCertificate(KeyPair keyPair) throws Exception {
  Date from = new Date();
  Date to = new GregorianCalendar(2037, Calendar.DECEMBER, 31).getTime();
  X500Name subject = new X500Name("CN=localhost");
  SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
  X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(
      subject,
      new BigInteger(64, new SecureRandom()),
      from,
      to,
      subject,
      subPubKeyInfo
  );
  AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA512WITHRSA");
  AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
  ContentSigner contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
      .build(PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded()));
  X509CertificateHolder certHolder = certBuilder.build(contentSigner);
  return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder);
}
 
Example #6
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 #7
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 #8
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 #9
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 #10
Source File: PkiUtil.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private static X509Certificate selfsign(PKCS10CertificationRequest inputCSR, String publicAddress, KeyPair signKey)
        throws Exception {

    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder()
            .find("SHA256withRSA");
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder()
            .find(sigAlgId);

    AsymmetricKeyParameter akp = PrivateKeyFactory.createKey(signKey.getPrivate()
            .getEncoded());

    Calendar cal = Calendar.getInstance();
    Date currentTime = cal.getTime();
    cal.add(Calendar.YEAR, CERT_VALIDITY_YEAR);
    Date expiryTime = cal.getTime();

    X509v3CertificateBuilder myCertificateGenerator = new X509v3CertificateBuilder(
            new X500Name(String.format("cn=%s", publicAddress)), new BigInteger("1"), currentTime, expiryTime, inputCSR.getSubject(),
            inputCSR.getSubjectPublicKeyInfo());

    ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
            .build(akp);

    X509CertificateHolder holder = myCertificateGenerator.build(sigGen);

    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    return (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(holder.toASN1Structure().getEncoded()));
}
 
Example #11
Source File: TestKeyStoreGenerator.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@NotNull
private ContentSigner createECContentSigner(final KeyPair keyPair) throws Exception {
    final AlgorithmIdentifier signatureAlgorithmId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withECDSA");
    final AlgorithmIdentifier digestAlgorithmId = new DefaultDigestAlgorithmIdentifierFinder().find(signatureAlgorithmId);

    final byte[] encoded = keyPair.getPrivate().getEncoded();
    final AsymmetricKeyParameter privateKey = PrivateKeyFactory.createKey(encoded);

    return new BcECContentSignerBuilder(signatureAlgorithmId, digestAlgorithmId).build(privateKey);
}
 
Example #12
Source File: TestKeyStoreGenerator.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@NotNull
private ContentSigner createRSAContentSigner(final KeyPair keyPair) throws Exception {
    final AlgorithmIdentifier signatureAlgorithmId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA");
    final AlgorithmIdentifier digestAlgorithmId = new DefaultDigestAlgorithmIdentifierFinder().find(signatureAlgorithmId);

    final byte[] encoded = keyPair.getPrivate().getEncoded();
    final AsymmetricKeyParameter privateKey = PrivateKeyFactory.createKey(encoded);

    return new BcRSAContentSignerBuilder(signatureAlgorithmId, digestAlgorithmId).build(privateKey);
}
 
Example #13
Source File: Certificates.java    From vertx-config with Apache License 2.0 5 votes vote down vote up
/**
 * See http://www.programcreek.com/java-api-examples/index.php?api=org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder
 *
 * @param keyPair The RSA keypair with which to generate the certificate
 * @param issuer  The issuer (and subject) to use for the certificate
 * @return An X509 certificate
 * @throws IOException
 * @throws OperatorCreationException
 * @throws CertificateException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws SignatureException
 */
private static X509Certificate generateCert(final KeyPair keyPair, final String issuer) throws IOException, OperatorCreationException,
  CertificateException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException,
  SignatureException {
  final String subject = issuer;
  final X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(
    new X500Name(issuer),
    BigInteger.ONE,
    new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30),
    new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)),
    new X500Name(subject),
    SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded())
  );

  final GeneralNames subjectAltNames = new GeneralNames(new GeneralName(GeneralName.iPAddress, "127.0.0.1"));
  certificateBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.subjectAlternativeName, false, subjectAltNames);

  final AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1WithRSAEncryption");
  final AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
  final BcContentSignerBuilder signerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId);
  final AsymmetricKeyParameter keyp = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded());
  final ContentSigner signer = signerBuilder.build(keyp);
  final X509CertificateHolder x509CertificateHolder = certificateBuilder.build(signer);

  final X509Certificate certificate = new JcaX509CertificateConverter()
    .getCertificate(x509CertificateHolder);
  certificate.checkValidity(new Date());
  certificate.verify(keyPair.getPublic());
  return certificate;
}
 
Example #14
Source File: CertificateUtils.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the content signer for generation of Version 1 {@link java.security.cert.X509Certificate}.
 *
 * @param privateKey the private key
 *
 * @return the content signer
 */
public static ContentSigner createSigner(PrivateKey privateKey) {
    try {
        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256WithRSAEncryption");
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);

        return new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
                .build(PrivateKeyFactory.createKey(privateKey.getEncoded()));
    } catch (Exception e) {
        throw new RuntimeException("Could not create content signer.", e);
    }
}
 
Example #15
Source File: SslConfigurer.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
private X509Certificate createCert(KeyPair keyPair, String signatureAlgoritm, String domainName)
  throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, OperatorCreationException, CertificateException, IOException {
  
  RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
  RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
  
  AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(signatureAlgoritm);
  AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
  BcContentSignerBuilder sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId);
  
  ASN1InputStream publicKeyStream = new ASN1InputStream(rsaPublicKey.getEncoded());
  SubjectPublicKeyInfo pubKey = SubjectPublicKeyInfo.getInstance(publicKeyStream.readObject());
  publicKeyStream.close();
  
  X509v3CertificateBuilder v3CertBuilder = new X509v3CertificateBuilder(
      new X500Name("CN=" + domainName + ", OU=None, O=None L=None, C=None"),
      BigInteger.valueOf(Math.abs(new SecureRandom().nextInt())),
      new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30),
      new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365*10)),
      new X500Name("CN=" + domainName + ", OU=None, O=None L=None, C=None"),
      pubKey);
  
  RSAKeyParameters keyParams = new RSAKeyParameters(true, rsaPrivateKey.getPrivateExponent(), rsaPrivateKey.getModulus());
  ContentSigner contentSigner = sigGen.build(keyParams);
  
  X509CertificateHolder certificateHolder = v3CertBuilder.build(contentSigner);
  
  JcaX509CertificateConverter certConverter = new JcaX509CertificateConverter().setProvider("BC");
  return certConverter.getCertificate(certificateHolder);
}
 
Example #16
Source File: Certificates.java    From icure-backend with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a Master certificate for ICure.
 */
public static X509Certificate createMasterCertificateV3(PublicKey publicKey, PrivateKey privateKey) throws Exception {
	X500Name 	issuer = new X500Name("C=BE, O=Taktik, OU=ICureCloud, CN=ICureCloud");
	X500Name 	subject = new X500Name("C=BE, O=Taktik, OU=ICureCloud, CN=ICureCloud"); // self signed
	BigInteger 	serial = BigInteger.valueOf(RSAKeysUtils.random.nextLong());
	Date 		notBefore = new Date(System.currentTimeMillis() - 10000);
	Date		notAfter = new Date(System.currentTimeMillis() + 24L * 3600 * 1000);
	
	SubjectPublicKeyInfo spki = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
	
	X509v3CertificateBuilder x509v3CertBuilder = new X509v3CertificateBuilder(issuer, serial, notBefore, notAfter, subject, spki);
	x509v3CertBuilder.addExtension(X509Extension.basicConstraints, true, new BasicConstraints(true)); // icure is CA

	// Create a content signer
	AlgorithmIdentifier signatureAlgorithmId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA");
	AlgorithmIdentifier digestAlgorithmId = new DefaultDigestAlgorithmIdentifierFinder().find(signatureAlgorithmId);
	AsymmetricKeyParameter akp = PrivateKeyFactory.createKey(privateKey.getEncoded());
	ContentSigner contentSigner =  new BcRSAContentSignerBuilder(signatureAlgorithmId, digestAlgorithmId).build(akp);

	X509CertificateHolder holder = x509v3CertBuilder.build(contentSigner);
	Certificate certificateStructure = holder.toASN1Structure();
	X509Certificate certificate = convertToJavaCertificate(certificateStructure);
	
	certificate.verify(publicKey);

	return certificate;
}
 
Example #17
Source File: ElasticsearchCluster.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private static ContentSigner newSigner(PrivateKey privateKey, String algo) {
    try {
        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algo);
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);

        return new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
                .build(PrivateKeyFactory.createKey(privateKey.getEncoded()));
    } catch (OperatorCreationException | IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #18
Source File: KeyGenerator.java    From chvote-1-0 with GNU Affero General Public License v3.0 5 votes vote down vote up
private ContentSigner createSigner(KeyPair keyPair) throws PropertyConfigurationException, OperatorCreationException {
    ContentSigner signer;
    String hashAlgo = propertyConfigurationService.getConfigValue(CERT_HASH_ALGORITHM);
    if (keyPair.getPrivate() instanceof RSAPrivateKey) {
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(hashAlgo + "withRSA");
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
        signer = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(
                new RSAKeyParameters(true, privateKey.getModulus(), privateKey.getPrivateExponent())
        );
    } else {
        throw new KeyGenerationRuntimeException("Unsupported key type");
    }
    return signer;
}
 
Example #19
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 #20
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 #21
Source File: CertGen.java    From snowblossom with Apache License 2.0 4 votes vote down vote up
/**
 * @param key_pair Key pair to use to sign the cert inner signed message, the node key
 * @param tls_wkp The temporary key to use just for this cert and TLS sessions
 * @param spec Address for 'key_pair'
 */
public static X509Certificate generateSelfSignedCert(WalletKeyPair key_pair, WalletKeyPair tls_wkp, AddressSpec spec)
  throws Exception
{

  AddressSpecHash address_hash = AddressUtil.getHashForSpec(spec);
  String address = AddressUtil.getAddressString(Globals.NODE_ADDRESS_STRING, address_hash);


  byte[] encoded_pub= tls_wkp.getPublicKey().toByteArray();
  SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(
    ASN1Sequence.getInstance(encoded_pub));

  String dn=String.format("CN=%s, O=Snowblossom", address);
  X500Name issuer = new X500Name(dn);
  BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());
  Date notBefore = new Date(System.currentTimeMillis());
  Date notAfter = new Date(System.currentTimeMillis() + 86400000L * 365L * 10L);
  X500Name subject = issuer;

  X509v3CertificateBuilder cert_builder = new X509v3CertificateBuilder(
    issuer, serial, notBefore, notAfter, subject, subjectPublicKeyInfo);

  //System.out.println(org.bouncycastle.asn1.x509.Extension.subjectAlternativeName);
  ASN1ObjectIdentifier snow_claim_oid = new ASN1ObjectIdentifier("2.5.29.134");

  //System.out.println(spec);

  SignedMessagePayload payload = SignedMessagePayload.newBuilder().setTlsPublicKey(tls_wkp.getPublicKey()).build();
  SignedMessage sm = MsgSigUtil.signMessage(spec, key_pair, payload);

  byte[] sm_data = sm.toByteString().toByteArray();

  cert_builder.addExtension(snow_claim_oid, true, sm_data);

  String algorithm = "SHA256withRSA";

  AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(tls_wkp.getPrivateKey().toByteArray());

  AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm);
  AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);

  //ContentSigner sigGen = new BcECContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);
  ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);

  X509CertificateHolder certificateHolder = cert_builder.build(sigGen);

  X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
  return cert;
}
 
Example #22
Source File: X509Util.java    From logback-gelf with GNU Lesser General Public License v2.1 4 votes vote down vote up
X509Certificate build(final String commonName, final String... subjectAltName)
    throws IOException, OperatorCreationException, CertificateException,
    NoSuchAlgorithmException {

    final AlgorithmIdentifier sigAlgId =
        new DefaultSignatureAlgorithmIdentifierFinder().find(SIG_ALGORITHM);
    final AlgorithmIdentifier digAlgId =
        new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    final AsymmetricKeyParameter privateKeyAsymKeyParam =
        PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded());
    final SubjectPublicKeyInfo subPubKeyInfo =
        SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
    final ContentSigner sigGen;

    final X500Name issuer = new X500Name(CA_NAME);
    final X500NameBuilder x500NameBuilder = new X500NameBuilder();
    if (commonName != null) {
        x500NameBuilder.addRDN(BCStyle.CN, commonName);
    }
    x500NameBuilder.addRDN(BCStyle.O, "snakeoil");
    final X500Name name = x500NameBuilder.build();

    final Date from = Date.valueOf(validFrom);
    final Date to = Date.valueOf(validTo);
    final BigInteger sn = new BigInteger(64, new SecureRandom());
    final X509v3CertificateBuilder v3CertGen =
        new X509v3CertificateBuilder(issuer, sn, from, to, name, subPubKeyInfo);

    if (caCertificate != null) {
        sigGen = new JcaContentSignerBuilder(SIG_ALGORITHM).build(caPrivateKey);

        final JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
        v3CertGen.addExtension(Extension.authorityKeyIdentifier, false,
            extUtils.createAuthorityKeyIdentifier(caCertificate));
    } else {
        sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
            .build(privateKeyAsymKeyParam);
    }

    if (subjectAltName != null) {
        final GeneralName[] generalNames = Arrays.stream(subjectAltName)
            .map(s -> new GeneralName(GeneralName.dNSName, s))
            .toArray(GeneralName[]::new);

        v3CertGen.addExtension(Extension.subjectAlternativeName, false,
            new GeneralNames(generalNames).getEncoded());
    }

    final X509CertificateHolder certificateHolder = v3CertGen.build(sigGen);
    return new JcaX509CertificateConverter()
        .setProvider(BouncyCastleProvider.PROVIDER_NAME)
        .getCertificate(certificateHolder);
}
 
Example #23
Source File: Certificates.java    From icure-backend with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Creates a certificate for a healthcare party.
 */
public static X509Certificate createCertificateV3(PublicKey hcpartyPublicKey, HealthcareParty hcparty, String hcPartyEmail, PublicKey icurePublicKey, PrivateKey icurePrivateKey) throws Exception {
	//
	// Signers
	//
	Hashtable<org.bouncycastle.asn1.ASN1ObjectIdentifier, String> sAttrs = new Hashtable<>();
	Vector<org.bouncycastle.asn1.ASN1ObjectIdentifier> sOrder = new Vector<>();

	sAttrs.put(X509Principal.C, "BE");
	sAttrs.put(X509Principal.O, "Taktik");
	sAttrs.put(X509Principal.OU, "ICureCloud");
	sAttrs.put(X509Principal.EmailAddress, "[email protected]");
	sOrder.addElement(X509Principal.C);
	sOrder.addElement(X509Principal.O);
	sOrder.addElement(X509Principal.OU);
	sOrder.addElement(X509Principal.EmailAddress);

	X509Principal issuerX509Principal = new X509Principal(sOrder, sAttrs);
	X500Name issuer = new X500Name(issuerX509Principal.getName());

	//
	// Subjects
	//
	Hashtable<org.bouncycastle.asn1.ASN1ObjectIdentifier, String> attrs = new Hashtable<>();
	Vector<org.bouncycastle.asn1.ASN1ObjectIdentifier> order = new Vector<>();

	attrs.put(X509Principal.C, "BE");
	attrs.put(X509Principal.O, "organization-" + hcparty.getCompanyName());
	attrs.put(X509Principal.L, "location-" + hcparty.getId());
	attrs.put(X509Principal.CN, "cn-" + hcparty.getId());
	attrs.put(X509Principal.EmailAddress, hcPartyEmail);
	order.addElement(X509Principal.C);
	order.addElement(X509Principal.O);
	order.addElement(X509Principal.L);
	order.addElement(X509Principal.CN);
	order.addElement(X509Principal.EmailAddress);

	X509Principal subjectX509Principal = new X509Principal(order, attrs);
	X500Name subject = new X500Name(subjectX509Principal.getName());

	//
	// Other attrs
	//
	BigInteger 	serial = BigInteger.valueOf(RSAKeysUtils.random.nextLong());
	Date 		notBefore = new Date(System.currentTimeMillis() - 10000);
	Date		notAfter = new Date(System.currentTimeMillis() + 24L * 3600 * 1000);
	SubjectPublicKeyInfo spki = SubjectPublicKeyInfo.getInstance(hcpartyPublicKey.getEncoded());
	

	X509v3CertificateBuilder x509v3CertBuilder = new X509v3CertificateBuilder(issuer, serial, notBefore, notAfter, subject, spki);
	x509v3CertBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(false)); // hcparty is not CA
	x509v3CertBuilder.addExtension(Extension.subjectKeyIdentifier, true, new SubjectKeyIdentifier(hcpartyPublicKey.getEncoded()));
	x509v3CertBuilder.addExtension(Extension.authorityKeyIdentifier, true, new AuthorityKeyIdentifierStructure(icurePublicKey));

	//
	// Create a content signer
	//
	AlgorithmIdentifier signatureAlgorithmId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA");
	AlgorithmIdentifier digestAlgorithmId = new DefaultDigestAlgorithmIdentifierFinder().find(signatureAlgorithmId);
	AsymmetricKeyParameter akp = PrivateKeyFactory.createKey(icurePrivateKey.getEncoded());
	ContentSigner contentSigner =  new BcRSAContentSignerBuilder(signatureAlgorithmId, digestAlgorithmId).build(akp);

	//
	// Build the certificate
	//
	X509CertificateHolder holder = x509v3CertBuilder.build(contentSigner);
	Certificate certificateStructure = holder.toASN1Structure();
	X509Certificate certificate = convertToJavaCertificate(certificateStructure);
	
	certificate.verify(icurePublicKey);

	return certificate;
}
 
Example #24
Source File: DefaultApprover.java    From hadoop-ozone with Apache License 2.0 4 votes vote down vote up
/**
 * Sign function signs a Certificate.
 * @param config - Security Config.
 * @param caPrivate - CAs private Key.
 * @param caCertificate - CA Certificate.
 * @param validFrom - Begin Da te
 * @param validTill - End Date
 * @param certificationRequest - Certification Request.
 * @param scmId - SCM id.
 * @param clusterId - Cluster id.
 * @return Signed Certificate.
 * @throws IOException - On Error
 * @throws OperatorCreationException - on Error.
 */
@SuppressWarnings("ParameterNumber")
public  X509CertificateHolder sign(
    SecurityConfig config,
    PrivateKey caPrivate,
    X509CertificateHolder caCertificate,
    Date validFrom,
    Date validTill,
    PKCS10CertificationRequest certificationRequest,
    String scmId,
    String clusterId) throws IOException, OperatorCreationException {

  AlgorithmIdentifier sigAlgId = new
      DefaultSignatureAlgorithmIdentifierFinder().find(
      config.getSignatureAlgo());
  AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder()
      .find(sigAlgId);

  AsymmetricKeyParameter asymmetricKP = PrivateKeyFactory.createKey(caPrivate
      .getEncoded());
  SubjectPublicKeyInfo keyInfo =
      certificationRequest.getSubjectPublicKeyInfo();

  // Get scmId and cluster Id from subject name.
  X500Name x500Name = certificationRequest.getSubject();
  String csrScmId = x500Name.getRDNs(BCStyle.OU)[0].getFirst().getValue().
      toASN1Primitive().toString();
  String csrClusterId = x500Name.getRDNs(BCStyle.O)[0].getFirst().getValue().
      toASN1Primitive().toString();

  if (!scmId.equals(csrScmId) || !clusterId.equals(csrClusterId)) {
    if (csrScmId.equalsIgnoreCase("null") &&
        csrClusterId.equalsIgnoreCase("null")) {
      // Special case to handle DN certificate generation as DN might not know
      // scmId and clusterId before registration. In secure mode registration
      // will succeed only after datanode has a valid certificate.
      String cn = x500Name.getRDNs(BCStyle.CN)[0].getFirst().getValue()
          .toASN1Primitive().toString();
      x500Name = SecurityUtil.getDistinguishedName(cn, scmId, clusterId);
    } else {
      // Throw exception if scmId and clusterId doesn't match.
      throw new SCMSecurityException("ScmId and ClusterId in CSR subject" +
          " are incorrect.");
    }
  }

  RSAKeyParameters rsa =
      (RSAKeyParameters) PublicKeyFactory.createKey(keyInfo);
  if (rsa.getModulus().bitLength() < config.getSize()) {
    throw new SCMSecurityException("Key size is too small in certificate " +
        "signing request");
  }
  X509v3CertificateBuilder certificateGenerator =
      new X509v3CertificateBuilder(
          caCertificate.getSubject(),
          // Serial is not sequential but it is monotonically increasing.
          BigInteger.valueOf(Time.monotonicNowNanos()),
          validFrom,
          validTill,
          x500Name, keyInfo);

  ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
      .build(asymmetricKP);

  return certificateGenerator.build(sigGen);

}
 
Example #25
Source File: CommonUtil.java    From gmhelper with Apache License 2.0 4 votes vote down vote up
public static AlgorithmIdentifier findDigestAlgorithmIdentifier(String algoName) {
    DefaultDigestAlgorithmIdentifierFinder digFinder = new DefaultDigestAlgorithmIdentifierFinder();
    return digFinder.find(findSignatureAlgorithmIdentifier(algoName));
}
 
Example #26
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 #27
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 #28
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 #29
Source File: PacketProxyCAPerUser.java    From PacketProxy with Apache License 2.0 4 votes vote down vote up
private void generateKeyStore(String ksPath) throws Exception {
	KeyStore ks;
	KeyPair CAKeyPair = super.genRSAKeyPair();
	
	// 各ユーザ用のキーストアを作るためのテンプレートを取得
	try (InputStream input = this.getClass().getResourceAsStream("/certificates/user.ks")) {
		ks = KeyStore.getInstance("JKS");
		ks.load(input, password);
	}
	
	int serialNumber = 0;
	do {
		serialNumber = SecureRandom.getInstance("SHA1PRNG").nextInt();
	} while (serialNumber <= 0);

	String x500Name = String.format("C=PacketProxy, ST=PacketProxy, L=PacketProxy, O=PacketProxy, OU=PacketProxy CA, CN=PacketProxy per-user CA (%x)", serialNumber);
	Date from = new Date();
	Calendar cal = Calendar.getInstance();
	cal.setTime(from);
	cal.add(Calendar.YEAR, 30);
	Date to = cal.getTime();

	X509v3CertificateBuilder caRootBuilder = new X509v3CertificateBuilder(
			new X500Name(x500Name),
			BigInteger.valueOf(serialNumber),
			from,
			to,
			new X500Name(x500Name),
			SubjectPublicKeyInfo.getInstance(CAKeyPair.getPublic().getEncoded()));
       
	/* CA: X509 Extensionsの設定(CA:true, pathlen:0) */
	caRootBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(0)); 
	
       AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA");
       AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
       ContentSigner signer = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(PrivateKeyFactory.createKey(CAKeyPair.getPrivate().getEncoded()));
       X509CertificateHolder signedRoot = caRootBuilder.build(signer);
	
	// 新しいKeyStoreの生成
	KeyStore newks = KeyStore.getInstance("JKS");
	newks.load(null, password);
	
	// 証明書と秘密鍵の登録
	CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
	newks.setKeyEntry(
			"root",
			CAKeyPair.getPrivate(),
			password,
			new Certificate[]{ certFactory.generateCertificate(new ByteArrayInputStream(signedRoot.getEncoded())) });
	
	File newksfile = new File(ksPath);
	newksfile.getParentFile().mkdirs();
	newksfile.createNewFile();
	newksfile.setWritable(false, false);
	newksfile.setWritable(true);
	newksfile.setReadable(false, false);
	newksfile.setReadable(true);
	try (FileOutputStream fos = new FileOutputStream(ksPath)) {
	    newks.store(fos, password);
	}
}
 
Example #30
Source File: CA.java    From PacketProxy with Apache License 2.0 4 votes vote down vote up
protected ContentSigner createSigner() throws Exception {
	AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA");
	AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
	return new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(PrivateKeyFactory.createKey(keyStoreCAPrivateKey.getEncoded()));
}