/** Build a sample V3 certificate to use as an end entity certificate */
 public static X509Certificate buildEndEntityCert(
     PublicKey entityKey, PrivateKey caKey, X509Certificate caCert) throws Exception {
   X509v3CertificateBuilder certBldr =
       new JcaX509v3CertificateBuilder(
           caCert.getSubjectX500Principal(),
           BigInteger.valueOf(1),
           new Date(System.currentTimeMillis()),
           new Date(System.currentTimeMillis() + VALIDITY_PERIOD),
           new X500Principal("CN=Test End Entity Certificate"),
           entityKey);
   JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
   certBldr
       .addExtension(
           Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert))
       .addExtension(
           Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(entityKey))
       .addExtension(Extension.basicConstraints, true, new BasicConstraints(false))
       .addExtension(
           Extension.keyUsage,
           true,
           new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
   ContentSigner signer =
       new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(caKey);
   return new JcaX509CertificateConverter()
       .setProvider("BC")
       .getCertificate(certBldr.build(signer));
 }
  private static X509Certificate getSelfCertificate(
      String myname, long validity, String sigAlg, KeyPair keyPair, String provider)
      throws OperatorCreationException, CertificateException {
    final long currentTime = new Date().getTime();
    final Date firstDate = new Date(currentTime - 24 * 60 * 60 * 1000);
    final Date lastDate = new Date(currentTime + validity * 1000);

    // Add all mandatory attributes
    if (LOG.isDebugEnabled()) {
      LOG.debug("keystore signing algorithm " + sigAlg);
    }

    final PublicKey publicKey = keyPair.getPublic();
    if (publicKey == null) {
      throw new IllegalArgumentException("Public key is null");
    }

    X509v3CertificateBuilder cg =
        new JcaX509v3CertificateBuilder(
            new X500Principal(myname),
            BigInteger.valueOf(firstDate.getTime()),
            firstDate,
            lastDate,
            new X500Principal(myname),
            publicKey);
    final JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder(sigAlg);
    contentSignerBuilder.setProvider(provider);

    final ContentSigner contentSigner = contentSignerBuilder.build(keyPair.getPrivate());

    return new JcaX509CertificateConverter().getCertificate(cg.build(contentSigner));
  }
 /** Build a sample V3 certificate to use as an intermediate CA certificate */
 public static X509Certificate buildIntermediateCert(
     PublicKey intKey, PrivateKey caKey, X509Certificate caCert) throws Exception {
   X509v3CertificateBuilder certBldr =
       new JcaX509v3CertificateBuilder(
           caCert.getSubjectX500Principal(),
           BigInteger.valueOf(1),
           new Date(),
           sdf.parse("2016-07-06 06:06:06"),
           new X500Principal("CN=Test CA Certificate"),
           intKey);
   JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
   certBldr
       .addExtension(
           Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert))
       .addExtension(
           Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(intKey))
       .addExtension(Extension.basicConstraints, true, new BasicConstraints(0))
       .addExtension(
           Extension.keyUsage,
           true,
           new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));
   ContentSigner signer =
       new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(caKey);
   return new JcaX509CertificateConverter()
       .setProvider("BC")
       .getCertificate(certBldr.build(signer));
 }
  private static X509CertificateHolder makeV3Certificate(
      KeyPair subKP, String _subDN, KeyPair issKP, String _issDN)
      throws GeneralSecurityException, IOException, OperatorCreationException, CertException {

    PublicKey subPub = subKP.getPublic();
    PrivateKey issPriv = issKP.getPrivate();
    PublicKey issPub = issKP.getPublic();

    X509v3CertificateBuilder v1CertGen =
        new JcaX509v3CertificateBuilder(
            new X500Name(_issDN),
            BigInteger.valueOf(System.currentTimeMillis()),
            new Date(System.currentTimeMillis()),
            new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 100)),
            new X500Name(_subDN),
            subPub);

    ContentSigner signer =
        new JcaContentSignerBuilder("SHA1WithRSA").setProvider(BC).build(issPriv);

    X509CertificateHolder certHolder = v1CertGen.build(signer);

    ContentVerifierProvider verifier =
        new JcaContentVerifierProviderBuilder().setProvider(BC).build(issPub);

    assertTrue(certHolder.isSignatureValid(verifier));

    return certHolder;
  }
 public static void checkOrCreateKeyStore(
     final String file, final String password, final String domainName)
     throws IllegalArgumentException, OperatorCreationException {
   final String hostname;
   if ("0.0.0.0".equals(domainName)) {
     hostname = "localhost";
   } else {
     hostname = domainName;
   }
   try {
     KeyStore ks = KeyStore.getInstance("JKS");
     File keyStoreFile = new File(file);
     if (!keyStoreFile.exists()) {
       keyStoreFile.createNewFile();
       ks.load(null, null);
       KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
       keyPairGenerator.initialize(1024);
       KeyPair KPair = keyPairGenerator.generateKeyPair();
       X509v3CertificateBuilder v3CertGen =
           new X509v3CertificateBuilder(
               new X500Name("CN=" + hostname + ", OU=None, O=None L=None, C=None"),
               BigInteger.valueOf(System.currentTimeMillis()),
               new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30),
               new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)),
               new X500Name("CN=" + hostname + ", OU=None, O=None L=None, C=None"),
               SubjectPublicKeyInfo.getInstance(KPair.getPublic().getEncoded()));
       AlgorithmIdentifier sigAlgId =
           new DefaultSignatureAlgorithmIdentifierFinder().find("SHA512withRSA");
       AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
       AsymmetricKeyParameter foo = PrivateKeyFactory.createKey(KPair.getPrivate().getEncoded());
       ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(foo);
       X509CertificateHolder PKCertificateHolder = v3CertGen.build(sigGen);
       X509CertificateStructure eeX509CertificateStructure = PKCertificateHolder.toASN1Structure();
       CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
       X509Certificate cert;
       try (InputStream is1 = new ByteArrayInputStream(eeX509CertificateStructure.getEncoded())) {
         cert = (X509Certificate) cf.generateCertificate(is1);
       }
       ks.setKeyEntry(
           "siesta",
           KPair.getPrivate(),
           password.toCharArray(),
           new java.security.cert.Certificate[] {cert});
       ks.store(new FileOutputStream(file), password.toCharArray());
     }
   } catch (GeneralSecurityException | IOException | IllegalStateException ex) {
     throw new IllegalArgumentException("Error creating keystore, please manually create one", ex);
   }
 }
 /** Build a sample V3 certificate to use as a CA root certificate */
 public static X509Certificate buildCARootCertV3(KeyPair keyPair) throws Exception {
   X500Name issuer =
       new X500Name("CN=Test Root Certificate,OU=JL,O=JL Corporation,L=SH_L,ST=SH,C=CN");
   BigInteger serial = BigInteger.valueOf(1);
   Date notBefore = new Date();
   Date notAfter = sdf.parse("2017-07-07 07:07:07");
   X500Name subject =
       new X500Name("CN=Test Root Certificate,OU=JL,O=JL Corporation,L=SH_L,ST=SH,C=CN");
   PublicKey publicKey = keyPair.getPublic();
   X509v3CertificateBuilder certBldr =
       new JcaX509v3CertificateBuilder(issuer, serial, notBefore, notAfter, subject, publicKey);
   ContentSigner signer =
       new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(keyPair.getPrivate());
   return new JcaX509CertificateConverter()
       .setProvider("BC")
       .getCertificate(certBldr.build(signer));
 }
Beispiel #7
0
 private X509Certificate createX509Certificate(
     X509v3CertificateBuilder certificateBuilder, PrivateKey privateRootKey)
     throws OperatorCreationException, CertificateException {
   ContentSigner signer =
       new JcaContentSignerBuilder("SHA256WithRSAEncryption")
           .setProvider(bouncyCastleProvider)
           .build(privateRootKey);
   return new JcaX509CertificateConverter()
       .setProvider(bouncyCastleProvider)
       .getCertificate(certificateBuilder.build(signer));
 }
  public X509v3CertificateBuilder applyExtension(X509v3CertificateBuilder certificateGenerator)
      throws CertIOException {

    BasicConstraints bc = null;

    if (((BasicConstraintField) certificateField).getIsCA() == false) {
      bc = new BasicConstraints(false);
    } else {
      bc = new BasicConstraints(((BasicConstraintField) certificateField).getPathLength());
    }

    certificateGenerator.addExtension(
        X509Extension.basicConstraints, certificateField.getCritical(), bc);
    return (certificateGenerator);
  }
  /**
   * 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);
    }
  }
Beispiel #10
0
 private X509Certificate buildRootCert(String domain, KeyPair _keyPair) throws Exception {
   X509v3CertificateBuilder certificateBuilder = createX509v3CertificateBuilder(domain, _keyPair);
   certificateBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
   return createX509Certificate(certificateBuilder, _keyPair.getPrivate());
 }