org.bouncycastle.operator.OperatorCreationException Java Examples

The following examples show how to use org.bouncycastle.operator.OperatorCreationException. 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: CsrBuilderImpl.java    From java-certificate-authority with Apache License 2.0 7 votes vote down vote up
@Override
public CsrWithPrivateKey generateRequest(final DistinguishedName dn) {
  final KeyPair pair = KeysUtil.generateKeyPair();
  try {
    final PrivateKey privateKey = pair.getPrivate();
    final PublicKey publicKey = pair.getPublic();
    final X500Name x500Name = dn.getX500Name();
    final ContentSigner signGen = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM)
        .build(privateKey);
    final PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(
        x500Name, publicKey);
    final PKCS10CertificationRequest csr = builder.build(signGen);
    return new CsrWithPrivateKeyImpl(csr, privateKey);
  } catch (final OperatorCreationException e) {
    throw new CaException(e);
  }
}
 
Example #2
Source File: MutualAuthenticationSettingsPanel.java    From Spark with Apache License 2.0 6 votes vote down vote up
private void createSelfSignedCertificate() {
idControll.setUpData(commonNameField.getText(), organizationUnitField.getText(), organizationField.getText(), countryField.getText(),
	cityField.getText());
try {
    KeyPair keyPair = idControll.createKeyPair();

    X509Certificate cert = idControll.createSelfSignedCertificate(keyPair);
           if (saveCertToFile.isSelected()) {
               PemBuilder pemBuilder = new PemHelper().new PemBuilder();
               pemBuilder.add(keyPair.getPrivate());
               pemBuilder.add(cert);
               pemBuilder.saveToPemFile(IdentityController.CERT_FILE);
               JOptionPane.showMessageDialog(null,
                       Res.getString("dialog.self.signed.certificate.has.been.created") + IdentityController.SECURITY_DIRECTORY.toString());
           } else {
               try {
                   idControll.addEntryToKeyStore(cert, keyPair.getPrivate());
               } catch (HeadlessException | InvalidNameException | KeyStoreException e) {
                       Log.error("Couldn't save entry to IdentityStore", e);
               }
           }
} catch (NoSuchAlgorithmException | NoSuchProviderException | IOException | OperatorCreationException | CertificateException e1) {
    Log.error("Couldn't create Self Signed Certificate", e1);
}
   }
 
Example #3
Source File: SSLEngineFactory.java    From NetBare with MIT License 6 votes vote down vote up
/**
 * Create a client {@link SSLEngine} with the remote server IP and port.
 *
 * @param host Remote server host.
 * @param port Remote server port.
 * @return A client {@link SSLEngine} instance.
 * @throws ExecutionException If an execution error has occurred.
 */
public SSLEngine createClientEngine(@NonNull final String host, int port) throws ExecutionException {
    SSLContext ctx = CLIENT_SSL_CONTEXTS.get(host, new Callable<SSLContext>() {
        @Override
        public SSLContext call() throws GeneralSecurityException, IOException,
                OperatorCreationException {
            return createClientContext(host);
        }
    });
    SSLEngine engine = ctx.createSSLEngine(host, port);
    List<String> ciphers = new LinkedList<>();
    for (String each : engine.getEnabledCipherSuites()) {
        if (!each.equals("TLS_DHE_RSA_WITH_AES_128_CBC_SHA") &&
                !each.equals("TLS_DHE_RSA_WITH_AES_256_CBC_SHA")) {
            ciphers.add(each);
        }
    }
    engine.setEnabledCipherSuites(ciphers.toArray(new String[0]));
    engine.setUseClientMode(true);
    engine.setNeedClientAuth(false);
    return engine;
}
 
Example #4
Source File: TestDefaultProfile.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * Test valid keys are validated correctly.
 *
 * @throws SCMSecurityException      - on Error.
 * @throws PKCSException             - on Error.
 * @throws OperatorCreationException - on Error.
 */
@Test
public void testVerifyCertificate() throws SCMSecurityException,
    PKCSException, OperatorCreationException {
  PKCS10CertificationRequest csr = new CertificateSignRequest.Builder()
      .addDnsName("hadoop.apache.org")
      .addIpAddress("8.8.8.8")
      .addServiceName("OzoneMarketingCluster001")
      .setCA(false)
      .setClusterID("ClusterID")
      .setScmID("SCMID")
      .setSubject("Ozone Cluster")
      .setConfiguration(configuration)
      .setKey(keyPair)
      .build();
  assertTrue(testApprover.verifyPkcs10Request(csr));
}
 
Example #5
Source File: BouncyCastleSslEngineSource.java    From CapturePacket with MIT License 6 votes vote down vote up
private SSLContext createServerContext(String commonName,
        SubjectAlternativeNameHolder subjectAlternativeNames)
        throws GeneralSecurityException, IOException,
        OperatorCreationException {

    MillisecondsDuration duration = new MillisecondsDuration();

    KeyStore ks = CertificateHelper.createServerCertificate(commonName,
            subjectAlternativeNames, authority, caCert, caPrivKey);
    KeyManager[] keyManagers = CertificateHelper.getKeyManagers(ks,
            authority);

    SSLContext result = CertificateHelper.newServerContext(keyManagers);

    LOG.info("Impersonated {} in {}ms", commonName, duration);
    return result;
}
 
Example #6
Source File: TestCRLCodec.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetX509CRLFromCRLHolder() throws IOException,
    OperatorCreationException, CertificateException, CRLException {

  X500Name issuer = x509CertificateHolder.getIssuer();
  Date now = new Date();
  X509v2CRLBuilder builder = new X509v2CRLBuilder(issuer, now);
  builder.addCRLEntry(x509CertificateHolder.getSerialNumber(), now,
                      CRLReason.cACompromise);

  JcaContentSignerBuilder contentSignerBuilder =
      new JcaContentSignerBuilder(securityConfig.getSignatureAlgo());

  contentSignerBuilder.setProvider(securityConfig.getProvider());
  PrivateKey privateKey = keyPair.getPrivate();
  X509CRLHolder cRLHolder =
      builder.build(contentSignerBuilder.build(privateKey));

  CRLCodec crlCodec = new CRLCodec(securityConfig);

  X509CRL crl = crlCodec.getX509CRL(cRLHolder);
  assertNotNull(crl);
}
 
Example #7
Source File: BouncyCastleSslEngineSource.java    From AndroidHttpCapture with MIT License 6 votes vote down vote up
private SSLContext createServerContext(String commonName,
        SubjectAlternativeNameHolder subjectAlternativeNames)
        throws GeneralSecurityException, IOException,
        OperatorCreationException {

    MillisecondsDuration duration = new MillisecondsDuration();

    KeyStore ks = CertificateHelper.createServerCertificate(commonName,
            subjectAlternativeNames, authority, caCert, caPrivKey);
    KeyManager[] keyManagers = CertificateHelper.getKeyManagers(ks,
            authority);

    SSLContext result = CertificateHelper.newServerContext(keyManagers);

    LOG.info("Impersonated {} in {}ms", commonName, duration);
    return result;
}
 
Example #8
Source File: OcspHandler.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public OcspHandler(String responderCertPath, String responderKeyPath)
        throws OperatorCreationException, GeneralSecurityException, IOException {
    final Certificate certificate = CertificateFactory.getInstance("X509")
            .generateCertificate(X509OCSPResponderTest.class.getResourceAsStream(responderCertPath));

    chain = new X509CertificateHolder[] {new X509CertificateHolder(certificate.getEncoded())};

    final AsymmetricKeyParameter publicKey = PublicKeyFactory.createKey(certificate.getPublicKey().getEncoded());

    subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(publicKey);

    final InputStream keyPairStream = X509OCSPResponderTest.class.getResourceAsStream(responderKeyPath);

    try (final PEMParser keyPairReader = new PEMParser(new InputStreamReader(keyPairStream))) {
        final PEMKeyPair keyPairPem = (PEMKeyPair) keyPairReader.readObject();
        privateKey = PrivateKeyFactory.createKey(keyPairPem.getPrivateKeyInfo());
    }
}
 
Example #9
Source File: CertificateSignRequest.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
public PKCS10CertificationRequest build() throws SCMSecurityException {
  Preconditions.checkNotNull(key, "KeyPair cannot be null");
  Preconditions.checkArgument(Strings.isNotBlank(subject), "Subject " +
      "cannot be blank");

  try {
    CertificateSignRequest csr = new CertificateSignRequest(subject, scmID,
        clusterID, key, config, createExtensions());
    return csr.generateCSR();
  } catch (IOException ioe) {
    throw new CertificateException(String.format("Unable to create " +
        "extension for certificate sign request for %s.", SecurityUtil
        .getDistinguishedName(subject, scmID, clusterID)), ioe.getCause());
  } catch (OperatorCreationException ex) {
    throw new CertificateException(String.format("Unable to create " +
        "certificate sign request for %s.", SecurityUtil
        .getDistinguishedName(subject, scmID, clusterID)),
        ex.getCause());
  }
}
 
Example #10
Source File: PEMImporter.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
public static KeyStore loadKeyStore(File certificateChainFile, File privateKeyFile, String keyPassword)
    throws IOException, GeneralSecurityException
{
    PrivateKey key;
    try {
        key = createPrivateKey(privateKeyFile, keyPassword);
    } catch (OperatorCreationException | IOException | GeneralSecurityException | PKCSException e) {
        throw new GeneralSecurityException("Private Key issues", e);
    }

    List<X509Certificate> certificateChain = readCertificateChain(certificateChainFile);
    if (certificateChain.isEmpty()) {
        throw new CertificateException("Certificate file does not contain any certificates: " + certificateChainFile);
    }

    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(null, null);
    keyStore.setKeyEntry("key", key, keyPassword.toCharArray(), certificateChain.stream().toArray(Certificate[]::new));
    return keyStore;
}
 
Example #11
Source File: OcspCertificateValidatorTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Generates a certificate with a specific public key signed by the issuer key.
 *
 * @param dn        the subject DN
 * @param publicKey the subject public key
 * @param issuerDn  the issuer DN
 * @param issuerKey the issuer private key
 * @return the certificate
 * @throws IOException               if an exception occurs
 * @throws NoSuchAlgorithmException  if an exception occurs
 * @throws CertificateException      if an exception occurs
 * @throws NoSuchProviderException   if an exception occurs
 * @throws SignatureException        if an exception occurs
 * @throws InvalidKeyException       if an exception occurs
 * @throws OperatorCreationException if an exception occurs
 */
private static X509Certificate generateIssuedCertificate(String dn, PublicKey publicKey, String issuerDn, PrivateKey issuerKey) throws IOException, NoSuchAlgorithmException,
        CertificateException, NoSuchProviderException, SignatureException, InvalidKeyException, OperatorCreationException {
    ContentSigner sigGen = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).setProvider(PROVIDER).build(issuerKey);
    SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
    Date startDate = new Date(YESTERDAY);
    Date endDate = new Date(ONE_YEAR_FROM_NOW);

    X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(
            new X500Name(issuerDn),
            BigInteger.valueOf(System.currentTimeMillis()),
            startDate, endDate,
            new X500Name(dn),
            subPubKeyInfo);

    X509CertificateHolder certificateHolder = v3CertGen.build(sigGen);
    return new JcaX509CertificateConverter().setProvider(PROVIDER)
            .getCertificate(certificateHolder);
}
 
Example #12
Source File: CryptoExceptionTest.java    From athenz with Apache License 2.0 6 votes vote down vote up
@Test
public void testCryptoExceptions() {

    CryptoException ex = new CryptoException();
    assertNotNull(ex);
    assertEquals(ex.getCode(), CryptoException.CRYPTO_ERROR);

    assertNotNull(new CryptoException(new NoSuchAlgorithmException()));
    assertNotNull(new CryptoException(new InvalidKeyException()));
    assertNotNull(new CryptoException(new NoSuchProviderException()));
    assertNotNull(new CryptoException(new SignatureException()));
    assertNotNull(new CryptoException(new FileNotFoundException()));
    assertNotNull(new CryptoException(new IOException()));
    assertNotNull(new CryptoException(new CertificateException()));
    assertNotNull(new CryptoException(new InvalidKeySpecException()));
    assertNotNull(new CryptoException(new OperatorCreationException("unit-test")));
    assertNotNull(new CryptoException(new PKCSException("unit-test")));
    assertNotNull(new CryptoException(new CMSException("unit-test")));

    ex = new CryptoException(CryptoException.CERT_HASH_MISMATCH, "X.509 Certificate hash mismatch");
    assertEquals(ex.getCode(), CryptoException.CERT_HASH_MISMATCH);
}
 
Example #13
Source File: X509CertificateGenerator.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
private X509Certificate generateVersion1(X500Name subject, X500Name issuer, Date validityStart, Date validityEnd, PublicKey publicKey,
		PrivateKey privateKey, SignatureType signatureType, BigInteger serialNumber) throws CryptoException {
	Date notBefore = validityStart == null ? new Date() : validityStart;
	Date notAfter = validityEnd == null ? new Date(notBefore.getTime() + TimeUnit.DAYS.toMillis(365)) : validityEnd;

	JcaX509v1CertificateBuilder certBuilder = new JcaX509v1CertificateBuilder(issuer, serialNumber, notBefore,
			notAfter, subject, publicKey);

	try {
		ContentSigner certSigner = new JcaContentSignerBuilder(signatureType.jce()).setProvider("BC").build(
				privateKey);
		return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certBuilder.build(certSigner));
	} catch (CertificateException | IllegalStateException | OperatorCreationException ex) {
		throw new CryptoException(res.getString("CertificateGenFailed.exception.message"), ex);
	}
}
 
Example #14
Source File: ApkUtils.java    From NBANDROID-V2 with Apache License 2.0 6 votes vote down vote up
public static boolean createNewStore(String storeType, File storeFile, char[] storePassword, DN dn) {
    if (storeType == null) {
        storeType = "jks";
    }
    try {
        KeyStore ks = KeyStore.getInstance(storeType);
        ks.load(null, null);
        Pair<PrivateKey, X509Certificate> generated = generateKeyAndCertificate("RSA", "SHA1withRSA", dn.validityYears, encodeDN(dn));
        ks.setKeyEntry(dn.alias, generated.getFirst(), dn.password, new Certificate[]{generated.getSecond()});
        FileOutputStream fos = new FileOutputStream(storeFile);
        boolean threw = true;
        try {
            ks.store(fos, storePassword);
            threw = false;
        } finally {
            Closeables.close(fos, threw);
        }
    } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | OperatorCreationException e) {
        return false;
    }
    return true;
}
 
Example #15
Source File: CMSSignedDataBuilder.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Note:
 * Section 5.1 of RFC 3852 [4] requires that, the CMS SignedData version be set to 3 if certificates from
 * SignedData is present AND (any version 1 attribute certificates are present OR any SignerInfo structures
 * are version 3 OR eContentType from encapContentInfo is other than id-data). Otherwise, the CMS
 * SignedData version is required to be set to 1.
 * CMS SignedData Version is handled automatically by BouncyCastle.
 *
 * @param parameters
 *            set of the driving signing parameters
 * @param contentSigner
 *            the contentSigner to get the hash of the data to be signed
 * @param signerInfoGeneratorBuilder
 *            the builder for the signer info generator
 * @param originalSignedData
 *            the original signed data if extending an existing signature. null otherwise.
 * @return the bouncycastle signed data generator which signs the document and adds the required signed and unsigned
 *         CMS attributes
 * @throws eu.europa.esig.dss.model.DSSException
 */
protected CMSSignedDataGenerator createCMSSignedDataGenerator(final CAdESSignatureParameters parameters, final ContentSigner contentSigner,
		final SignerInfoGeneratorBuilder signerInfoGeneratorBuilder, final CMSSignedData originalSignedData) throws DSSException {
	try {
		final CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
		final SignerInfoGenerator signerInfoGenerator = getSignerInfoGenerator(signerInfoGeneratorBuilder, contentSigner, parameters);

		generator.addSignerInfoGenerator(signerInfoGenerator);

		final List<CertificateToken> certificateChain = new LinkedList<>();
		if (originalSignedData != null) {

			generator.addSigners(originalSignedData.getSignerInfos());
			generator.addAttributeCertificates(originalSignedData.getAttributeCertificates());
			generator.addCRLs(originalSignedData.getCRLs());
			generator.addOtherRevocationInfo(id_pkix_ocsp_basic, originalSignedData.getOtherRevocationInfo(id_pkix_ocsp_basic));
			generator.addOtherRevocationInfo(id_ri_ocsp_response, originalSignedData.getOtherRevocationInfo(id_ri_ocsp_response));

			final Store<X509CertificateHolder> certificates = originalSignedData.getCertificates();
			final Collection<X509CertificateHolder> certificatesMatches = certificates.getMatches(null);
			for (final X509CertificateHolder certificatesMatch : certificatesMatches) {
				final CertificateToken token = DSSASN1Utils.getCertificate(certificatesMatch);
				if (!certificateChain.contains(token)) {
					certificateChain.add(token);
				}
			}
		}

		final JcaCertStore jcaCertStore = getJcaCertStore(certificateChain, parameters);
		generator.addCertificates(jcaCertStore);
		return generator;
	} catch (CMSException | OperatorCreationException e) {
		throw new DSSException(e);
	}
}
 
Example #16
Source File: BouncyCastleSslEngineSource.java    From LittleProxy-mitm with Apache License 2.0 5 votes vote down vote up
public void initializeServerCertificates(String commonName,
        SubjectAlternativeNameHolder subjectAlternativeNames)
        throws GeneralSecurityException, OperatorCreationException,
        IOException {

    KeyStore ks = CertificateHelper.createServerCertificate(commonName,
            subjectAlternativeNames, authority, caCert, caPrivKey);

    PrivateKey key = (PrivateKey) ks.getKey(authority.alias(),
            authority.password());
    exportPem(authority.aliasFile("-" + commonName + "-key.pem"), key);

    Object[] certs = ks.getCertificateChain(authority.alias());
    exportPem(authority.aliasFile("-" + commonName + "-cert.pem"), certs);
}
 
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: SSLContextBuilderTest.java    From tessera with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp()
        throws NoSuchAlgorithmException, OperatorCreationException, InvalidKeyException, IOException,
                KeyStoreException, SignatureException, NoSuchProviderException, CertificateException,
                URISyntaxException {
    keyStoreFile = Paths.get(tmpDir.getRoot().getPath(), "keystore");
    knownHostFile = Paths.get(tmpDir.getRoot().getPath(), "knownHosts");
    key = Paths.get(getClass().getResource("/key.pem").toURI());
    certificate = Paths.get(getClass().getResource("/cert.pem").toURI());
    trustedCertificates = Arrays.asList(certificate);
    sslContextBuilder = SSLContextBuilder.createBuilder(LOCALHOST, keyStoreFile, PASSWORD, keyStoreFile, PASSWORD);
    TlsUtils.create().generateKeyStoreWithSelfSignedCertificate(LOCALHOST, keyStoreFile, PASSWORD);
}
 
Example #19
Source File: BouncyCastleSecurityProviderTool.java    From Dream-Catcher with MIT License 5 votes vote down vote up
/**
 * Creates a ContentSigner that can be used to sign certificates with the given private key and signature algorithm.
 *
 * @param certAuthorityPrivateKey the private key to use to sign certificates
 * @param signatureAlgorithm      the algorithm to use to sign certificates
 * @return a ContentSigner
 */
private static ContentSigner getCertificateSigner(PrivateKey certAuthorityPrivateKey, String signatureAlgorithm) {
    try {
        return new JcaContentSignerBuilder(signatureAlgorithm)
                .build(certAuthorityPrivateKey);
    } catch (OperatorCreationException e) {
        throw new CertificateCreationException("Unable to create ContentSigner using signature algorithm: " + signatureAlgorithm, e);
    }
}
 
Example #20
Source File: CACertificateService.java    From flashback with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public X509Certificate createSignedCertificate(PublicKey publicKey, PrivateKey privateKey, String commonName,
    List<ASN1Encodable> sans)
    throws CertificateException, IOException, OperatorCreationException, NoSuchProviderException,
           NoSuchAlgorithmException, InvalidKeyException, SignatureException {
  BigInteger serial = getSerial();
  X500Name subject = getSubject(commonName);
  X500Name issuer = subject;

  X509v3CertificateBuilder x509v3CertificateBuilder =
      new JcaX509v3CertificateBuilder(issuer, serial, getValidDateFrom(), getValidDateTo(), subject, publicKey);
  buildExtensions(x509v3CertificateBuilder, publicKey);
  return createCertificate(privateKey, x509v3CertificateBuilder);
}
 
Example #21
Source File: SelfCertSignerFactory.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Override
public CertSigner create() {
    
    // extract the private key for this self cert signer
    
    final String pKeyFileName = System.getProperty(ZTSConsts.ZTS_PROP_SELF_SIGNER_PRIVATE_KEY_FNAME);
    final String pKeyPassword = System.getProperty(ZTSConsts.ZTS_PROP_SELF_SIGNER_PRIVATE_KEY_PASSWORD);
    final String csrDn = System.getProperty(ZTSConsts.ZTS_PROP_SELF_SIGNER_CERT_DN,
            "cn=Self Signed Athenz CA,o=Athenz,c=US");

    if (pKeyFileName == null) {
        LOGGER.error("No private key path available for Self Cert Signer Factory");
        return null;
    }
    
    File caKey = new File(pKeyFileName);
    PrivateKey caPrivateKey = Crypto.loadPrivateKey(caKey, pKeyPassword);
    
    // now generate a CSR for our own CA and self sign it
    
    String csr;
    try {
        csr = Crypto.generateX509CSR(caPrivateKey, csrDn, null);
    } catch (IllegalArgumentException | OperatorCreationException | IOException ex) {
        LOGGER.error("Unable to generate X509 CSR for dn: " + csrDn
                + ", error: " + ex.getMessage());
        return null;
    }
    
    // generate our self signed certificate
    
    X500Principal subject = new X500Principal(csrDn);
    X500Name issuer = X500Name.getInstance(subject.getEncoded());
    PKCS10CertificationRequest certReq = Crypto.getPKCS10CertRequest(csr);
    X509Certificate caCertificate = Crypto.generateX509Certificate(certReq,
            caPrivateKey, issuer, 30 * 24 * 60, true);

    return new SelfCertSigner(caPrivateKey, caCertificate);
}
 
Example #22
Source File: CloneCertificateTest.java    From SAMLRaider with MIT License 5 votes vote down vote up
@Test
public void exportClonedCertificate() throws CertificateException, IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, OperatorCreationException,
		IllegalStateException, SignatureException, InvalidKeySpecException {
	String outputFile = tempFolder.newFile("export_cloned.pem").toString();

	BurpCertificate clonedCertificate = certificateTabController.cloneCertificate(originalCertificate, new FakeBurpCertificateBuilder(originalCertificate.getSubject()));
	certificateTabController.exportCertificate(clonedCertificate, outputFile);

	String outputExpedted = "-----BEGIN CERTIFICATE-----MIIDmjCCA0SgAwIBAgIUTWsBgOGCuRA3PeIxfJJ1lHAuiTUwDQYJKoZIhvcNAQEFBQAwazELMAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxHzAdBgNVBAsTFnd3dy5xdW92YWRpc2dsb2JhbC5jb20xIDAeBgNVBAMTF1F1b1ZhZGlzIEdsb2JhbCBTU0wgSUNBMB4XDTEyMDgxNTEwNTY0OVoXDTE1MDgxNTEwNTY0OVowgYExCzAJBgNVBAYTAkNIMRMwEQYDVQQIEwpTdC4gR2FsbGVuMRMwEQYDVQQHEwpSYXBwZXJzd2lsMR4wHAYDVQQKExVIb2Noc2NodWxlIFJhcHBlcnN3aWwxEzARBgNVBAsTCklULVN5c3RlbXMxEzARBgNVBAMTCnd3dy5oc3IuY2gwWjANBgkqhkiG9w0BAQEFAANJADBGAkEAtKfkYXBXTxapcIKyK+WLaipil5hBm+EocqS9umJs+umQD3ar+xITnc5d5WVk+rK2VDFloEDGBoh0IOM9ke1+1wIBEaOCAakwggGlMA4GA1UdDwEB/wQEAwIFoDB0BggrBgEFBQcBAQRoMGYwKgYIKwYBBQUHMAGGHmh0dHA6Ly9vY3NwLnF1b3ZhZGlzZ2xvYmFsLmNvbTA4BggrBgEFBQcwAoYsaHR0cDovL3RydXN0LnF1b3ZhZGlzZ2xvYmFsLmNvbS9xdnNzbGljYS5jcnQwHQYDVR0OBBYEFHjRxyuQCYIPx1gmApOod9ESOMCrMC4GA1UdEQQnMCWCCnd3dy5oc3IuY2iCCmxvZy5oc3IuY2iBC3Jvb3RAaHNyLmNoMDsGA1UdHwQ0MDIwMKAuoCyGKmh0dHA6Ly9jcmwucXVvdmFkaXNnbG9iYWwuY29tL3F2c3NsaWNhLmNybDBRBgNVHSAESjBIMEYGDCsGAQQBvlgAAmQBATA2MDQGCCsGAQUFBwIBFihodHRwOi8vd3d3LnF1b3ZhZGlzZ2xvYmFsLmNvbS9yZXBvc2l0b3J5MB8GA1UdIwQYMBaAFDJNoU/q8K6Ztu6bByyECBFQi+J+MB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjANBgkqhkiG9w0BAQUFAANBAA5/x8tf24JfJoYHOYfHYtZi9v387k2q3UyNjBX1LkLo0iDCMuCUy68mXHF/dlFYZA1WE7ldYlQbaBN7vg6o9js=-----END CERTIFICATE-----";

	byte[] outputData = Files.readAllBytes(Paths.get(outputFile));
	String outputString = CertificateHelper.byteArrayToString(outputData).replaceAll("\r", "").replace("\n", "");

	assertEquals(outputExpedted, outputString);
}
 
Example #23
Source File: BouncyCastleSslEngineSource.java    From AndroidHttpCapture with MIT License 5 votes vote down vote up
/**
 * Generates an 1024 bit RSA key pair using SHA1PRNG. Thoughts: 2048 takes
 * much longer time on older CPUs. And for almost every client, 1024 is
 * sufficient.
 * 
 * Derived from Zed Attack Proxy (ZAP). ZAP is an HTTP/HTTPS proxy for
 * assessing web application security. Copyright 2011 [email protected]
 * Licensed under the Apache License, Version 2.0
 * 
 * @param commonName
 *            the common name to use in the server certificate
 * 
 * @param subjectAlternativeNames
 *            a List of the subject alternative names to use in the server
 *            certificate, could be empty, but must not be null
 * 
 * @see org.parosproxy.paros.security.SslCertificateServiceImpl.
 *      createCertForHost(String)
 * @see org.parosproxy.paros.network.SSLConnector.getTunnelSSLSocketFactory(
 *      String)
 */
public SSLEngine createCertForHost(final String commonName,
        final SubjectAlternativeNameHolder subjectAlternativeNames)
        throws GeneralSecurityException, OperatorCreationException,
        IOException, ExecutionException {
    if (commonName == null) {
        throw new IllegalArgumentException(
                "Error, 'commonName' is not allowed to be null!");
    }
    if (subjectAlternativeNames == null) {
        throw new IllegalArgumentException(
                "Error, 'subjectAlternativeNames' is not allowed to be null!");
    }

    SSLContext ctx;
    if (serverSSLContexts == null) {
        ctx = createServerContext(commonName, subjectAlternativeNames);
    } else {
        ctx = serverSSLContexts.get(commonName, new Callable<SSLContext>() {
            @Override
            public SSLContext call() throws Exception {
                return createServerContext(commonName,
                        subjectAlternativeNames);
            }
        });
    }
    return ctx.createSSLEngine();
}
 
Example #24
Source File: CertificateGenerator.java    From NetBare with MIT License 5 votes vote down vote up
/**
 * Generate a root keystore by a given {@link JKS}.
 *
 * @param jks A java keystore object.
 * @return A root {@link KeyStore}.
 */
public KeyStore generateRoot(JKS jks)
        throws KeyStoreException, CertificateException, NoSuchAlgorithmException,
        IOException, OperatorCreationException {
    KeyPair keyPair = generateKeyPair(ROOT_KEY_SIZE);

    X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    nameBuilder.addRDN(BCStyle.CN, jks.commonName());
    nameBuilder.addRDN(BCStyle.O, jks.organization());
    nameBuilder.addRDN(BCStyle.OU, jks.organizationalUnitName());
    X500Name issuer = nameBuilder.build();

    PublicKey pubKey = keyPair.getPublic();

    X509v3CertificateBuilder generator = new JcaX509v3CertificateBuilder(
            issuer, BigInteger.valueOf(randomSerial()), NOT_BEFORE, NOT_AFTER, issuer, pubKey);
    generator.addExtension(Extension.subjectKeyIdentifier, false,
            createSubjectKeyIdentifier(pubKey));
    generator.addExtension(Extension.basicConstraints, true,
            new BasicConstraints(true));

    KeyUsage usage = new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature |
            KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.cRLSign);
    generator.addExtension(Extension.keyUsage, false, usage);

    ASN1EncodableVector purposes = new ASN1EncodableVector();
    purposes.add(KeyPurposeId.id_kp_serverAuth);
    purposes.add(KeyPurposeId.id_kp_clientAuth);
    purposes.add(KeyPurposeId.anyExtendedKeyUsage);
    generator.addExtension(Extension.extendedKeyUsage, false,
            new DERSequence(purposes));

    X509Certificate cert = signCertificate(generator, keyPair.getPrivate());

    KeyStore result = KeyStore.getInstance(KEY_STORE_TYPE);
    result.load(null, null);
    result.setKeyEntry(jks.alias(), keyPair.getPrivate(), jks.password(),
            new Certificate[] { cert });
    return result;
}
 
Example #25
Source File: ComplianceToolModeConfigurationFactory.java    From verify-service-provider with MIT License 5 votes vote down vote up
private KeysAndCert createKeysAndCert(String serviceEntityId) throws IOException {
    KeysAndCert keysAndCert = new KeysAndCert(serviceEntityId);
    try {
        keysAndCert.generate();
    } catch (CertificateException | NoSuchAlgorithmException | OperatorCreationException e) {
        throw new RuntimeException(e);
    }
    return keysAndCert;
}
 
Example #26
Source File: BouncyCastleSslEngineSource.java    From CapturePacket with MIT License 5 votes vote down vote up
public void initializeServerCertificates(String commonName,
        SubjectAlternativeNameHolder subjectAlternativeNames)
        throws GeneralSecurityException, OperatorCreationException,
        IOException {

    KeyStore ks = CertificateHelper.createServerCertificate(commonName,
            subjectAlternativeNames, authority, caCert, caPrivKey);

    PrivateKey key = (PrivateKey) ks.getKey(authority.alias(),
            authority.password());
    exportPem(authority.aliasFile("-" + commonName + "-key.pem"), key);

    Object[] certs = ks.getCertificateChain(authority.alias());
    exportPem(authority.aliasFile("-" + commonName + "-cert.pem"), certs);
}
 
Example #27
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 #28
Source File: InstanceClientRefresh.java    From athenz with Apache License 2.0 5 votes vote down vote up
public static String generateCSR(String domainName, String serviceName,
        String instanceId, String dnsSuffix, PrivateKey key) {
    
    final String dn = "cn=" + domainName + "." + serviceName + ",o=Athenz";
    
    // now let's generate our dsnName field based on our principal's details
    
    StringBuilder dnsName = new StringBuilder(128);
    dnsName.append(serviceName);
    dnsName.append('.');
    dnsName.append(domainName.replace('.', '-'));
    dnsName.append('.');
    dnsName.append(dnsSuffix);
    
    GeneralName[] sanArray = new GeneralName[2];
    sanArray[0] = new GeneralName(GeneralName.dNSName, new DERIA5String(dnsName.toString()));
    
    // next we include our instance id
    
    StringBuilder dnsInstance = new StringBuilder(128);
    dnsInstance.append(instanceId);
    dnsInstance.append(".instanceid.athenz.");
    dnsInstance.append(dnsSuffix);
    
    sanArray[1] = new GeneralName(GeneralName.dNSName, new DERIA5String(dnsInstance.toString()));
    
    String csr = null;
    try {
        csr = Crypto.generateX509CSR(key, dn, sanArray);
    } catch (OperatorCreationException | IOException ex) {
        System.err.println(ex.getMessage());
    }
    
    return csr;
}
 
Example #29
Source File: Crypto.java    From athenz with Apache License 2.0 5 votes vote down vote up
public static String generateX509CSR(PrivateKey privateKey, String x500Principal,
                                     GeneralName[] sanArray) throws OperatorCreationException, IOException {
    final PublicKey publicKey = extractPublicKey(privateKey);
    ///CLOVER:OFF
    if (publicKey == null) {
        throw new CryptoException("Unable to extract public key from private key");
    }
    ///CLOVER:ON
    return generateX509CSR(privateKey, publicKey, x500Principal, sanArray);
}
 
Example #30
Source File: CaEmulator.java    From xipki with Apache License 2.0 5 votes vote down vote up
public ContentVerifierProvider getContentVerifierProvider(PublicKey publicKey)
    throws InvalidKeyException {
  Args.notNull(publicKey, "publicKey");

  String keyAlg = publicKey.getAlgorithm().toUpperCase();
  if ("EC".equals(keyAlg)) {
    keyAlg = "ECDSA";
  }

  BcContentVerifierProviderBuilder builder = VERIFIER_PROVIDER_BUILDER.get(keyAlg);
  if (builder == null) {
    if ("RSA".equals(keyAlg)) {
      builder = new BcRSAContentVerifierProviderBuilder(DFLT_DIGESTALG_IDENTIFIER_FINDER);
    } else if ("DSA".equals(keyAlg)) {
      builder = new BcDSAContentVerifierProviderBuilder(DFLT_DIGESTALG_IDENTIFIER_FINDER);
    } else if ("ECDSA".equals(keyAlg)) {
      builder = new BcECContentVerifierProviderBuilder(DFLT_DIGESTALG_IDENTIFIER_FINDER);
    } else {
      throw new InvalidKeyException("unknown key algorithm of the public key " + keyAlg);
    }
    VERIFIER_PROVIDER_BUILDER.put(keyAlg, builder);
  }

  AsymmetricKeyParameter keyParam = generatePublicKeyParameter(publicKey);
  try {
    return builder.build(keyParam);
  } catch (OperatorCreationException ex) {
    throw new InvalidKeyException("could not build ContentVerifierProvider: " + ex.getMessage(),
        ex);
  }
}