Example usage for java.security KeyPair getPrivate

List of usage examples for java.security KeyPair getPrivate

Introduction

In this page you can find the example usage for java.security KeyPair getPrivate.

Prototype

public PrivateKey getPrivate() 

Source Link

Document

Returns a reference to the private key component of this key pair.

Usage

From source file:com.thoughtworks.go.security.X509CertificateGenerator.java

public Registration createAndStoreCACertificates(File keystore) {
    Date startDate = new Date(0);
    String principalDn = "ou=Cruise Server primary certificate, cn=" + getHostname();

    try {//from  ww w.java  2  s.c  o  m
        KeyPair caKeyPair = generateKeyPair();
        X509Certificate caCertificate = createTypeOneX509Certificate(startDate, principalDn, caKeyPair);

        KeyPair intKeyPair = generateKeyPair();
        X509Certificate intermediateCertificate = createIntermediateCertificate(caKeyPair.getPrivate(),
                caCertificate, startDate, intKeyPair);

        Registration intermediateEntry = new Registration(intKeyPair.getPrivate(), intermediateCertificate);

        keyStoreManager.storeCACertificate(keystore, PASSWORD, caCertificate, intermediateEntry);

        return new Registration(intKeyPair.getPrivate(), intermediateCertificate, caCertificate);
    } catch (Exception e) {
        throw new RuntimeException("Couldn't create server certificates", e);
    }
}

From source file:edu.vt.alerts.android.library.tasks.RegistrationTask.java

private PKCS10CertificationRequest generateCSR(KeyPair keyPair) throws Exception {
    JcaPKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(
            new X500Name("CN=edu.vt.alerts.mobile.android"), keyPair.getPublic());

    ContentSigner signer = new JcaContentSignerBuilder(CSR_SIGNER_ALGORITHM).setProvider(CSR_SIGNER_PROVIDER)
            .build(keyPair.getPrivate());

    return builder.build(signer);
}

From source file:org.candlepin.service.impl.DefaultEntitlementCertServiceAdapter.java

/**
 * @param entitlements a map of entitlements indexed by pool ids to generate
 *        the certs of//w  ww. j ava2s .  c om
 * @param productMap a map of respective products indexed by pool id
 * @throws IOException
 * @throws GeneralSecurityException
 * @return entitlementCerts the respective entitlement certs indexed by pool
 *         id
 */
private Map<String, EntitlementCertificate> generateEntitlementCerts(Consumer consumer,
        Map<String, Entitlement> entitlements, Map<String, Product> productMap, boolean thisIsUeberCert)
        throws GeneralSecurityException, IOException {
    log.info("Generating entitlement cert for entitlements");
    KeyPair keyPair = keyPairCurator.getConsumerKeyPair(consumer);
    byte[] pemEncodedKeyPair = pki.getPemEncoded(keyPair.getPrivate());

    Map<String, CertificateSerial> serialMap = new HashMap<String, CertificateSerial>();
    for (Entry<String, Entitlement> entry : entitlements.entrySet()) {
        serialMap.put(entry.getKey(), new CertificateSerial(entry.getValue().getEndDate()));
    }

    // We need the sequence generated id before we create the
    // EntitlementCertificate, otherwise we could have used cascading create
    serialCurator.saveOrUpdateAll(serialMap);

    Map<String, EntitlementCertificate> entitlementCerts = new HashMap<String, EntitlementCertificate>();

    for (Entry<String, Entitlement> entry : entitlements.entrySet()) {
        Entitlement entitlement = entry.getValue();
        CertificateSerial serial = serialMap.get(entry.getKey());
        Product product = productMap.get(entry.getKey());

        log.info("Generating entitlement cert for entitlement: {}", entitlement);

        Set<Product> products = new HashSet<Product>(entitlement.getPool().getProvidedProducts());

        // If creating a certificate for a distributor, we need
        // to add any derived products as well so that their content
        // is available in the upstream certificate.
        products.addAll(getDerivedProductsForDistributor(entitlement));
        products.add(product);

        Map<String, EnvironmentContent> promotedContent = getPromotedContent(entitlement);
        String contentPrefix = getContentPrefix(entitlement, !thisIsUeberCert);

        log.info("Creating X509 cert for product: {}", product);
        log.debug("Provided products: {}", products);
        List<org.candlepin.model.dto.Product> productModels = v3extensionUtil.createProducts(product, products,
                contentPrefix, promotedContent, entitlement.getConsumer(), entitlement);

        X509Certificate x509Cert = createX509Certificate(entitlement, product, products, productModels,
                BigInteger.valueOf(serial.getId()), keyPair, !thisIsUeberCert);

        EntitlementCertificate cert = new EntitlementCertificate();
        cert.setSerial(serial);
        cert.setKeyAsBytes(pemEncodedKeyPair);

        log.info("Getting PEM encoded cert.");
        String pem = new String(this.pki.getPemEncoded(x509Cert));

        if (shouldGenerateV3(entitlement)) {
            log.debug("Generating v3 entitlement data");

            byte[] payloadBytes = v3extensionUtil.createEntitlementDataPayload(product, productModels,
                    entitlement, contentPrefix, promotedContent);

            String payload = "-----BEGIN ENTITLEMENT DATA-----\n";
            payload += Util.toBase64(payloadBytes);
            payload += "-----END ENTITLEMENT DATA-----\n";

            byte[] bytes = pki.getSHA256WithRSAHash(new ByteArrayInputStream(payloadBytes));
            String signature = "-----BEGIN RSA SIGNATURE-----\n";
            signature += Util.toBase64(bytes);
            signature += "-----END RSA SIGNATURE-----\n";

            pem += payload + signature;
        }

        cert.setCert(pem);
        cert.setEntitlement(entitlement);

        if (log.isDebugEnabled()) {
            log.debug("Generated cert serial number: {}", serial.getId());
            log.debug("Key: {}", cert.getKey());
            log.debug("Cert: {}", cert.getCert());
        }

        entitlement.getCertificates().add(cert);
        entitlementCerts.put(entry.getKey(), cert);
    }

    log.info("Persisting certs.");
    entCertCurator.saveOrUpdateAll(entitlementCerts.values(), false);

    return entitlementCerts;
}

From source file:org.cesecore.mock.authentication.SimpleAuthenticationProviderSessionBean.java

/**
 * This is the pug of authentication; loves everybody.
 *///from   w w  w  .  j ava2  s . co m
@Override
public AuthenticationToken authenticate(AuthenticationSubject subject) {

    // A small check if we have added a "fail" credential to the subject.
    // If we have we will return null, so we can test authentication failure.
    Set<?> usercredentials = subject.getCredentials();
    if ((usercredentials != null) && (usercredentials.size() > 0)) {
        Object o = usercredentials.iterator().next();
        if (o instanceof String) {
            String str = (String) o;
            if (StringUtils.equals("fail", str)) {
                if (log.isDebugEnabled()) {
                    log.debug("Found a 'fail' credential, returning null");
                }
                return null;
            }
        }
    }

    X509Certificate certificate = null;
    // If we have a certificate as input, use that, otherwise generate a self signed certificate
    Set<?> inputcreds = subject.getCredentials();
    if (inputcreds != null) {
        for (Object object : inputcreds) {
            if (object instanceof X509Certificate) {
                certificate = (X509Certificate) object;
                if (log.isDebugEnabled()) {
                    log.debug("Found a certificate credential that we will use, fp="
                            + CertTools.getFingerprintAsString(certificate));
                }
            }
        }
    }

    // If there was no certificate input, create a self signed
    if (certificate == null) {
        if (log.isDebugEnabled()) {
            log.debug("No certificate input, will create a self-signed one");
        }
        String dn = DEFAULT_DN;
        // If we have created a subject with an X500Principal we will use this DN to create the dummy certificate.
        if (subject != null) {
            Set<Principal> principals = subject.getPrincipals();
            if ((principals != null) && (principals.size() > 0)) {
                Principal p = principals.iterator().next();
                if (p instanceof X500Principal) {
                    X500Principal xp = (X500Principal) p;
                    dn = xp.getName();
                }
            }
        }
        KeyPair keys = null;
        try {
            keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
        } catch (InvalidAlgorithmParameterException e) {
            throw new InvalidAuthenticationTokenException("Could not create authentication token.", e);
        }
        try {
            certificate = CertTools.genSelfCert(dn, 365, null, keys.getPrivate(), keys.getPublic(),
                    AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true);
        } catch (CertificateEncodingException e) {
            throw new CertificateCreationException("Error encountered when creating certificate", e);
        } catch (IllegalStateException e) {
            throw new CertificateCreationException("Error encountered when creating certificate", e);
        } catch (OperatorCreationException e) {
            throw new CertificateCreationException("Error encountered when creating certificate", e);
        } catch (CertificateException e) {
            throw new CertificateCreationException("Error encountered when creating certificate", e);
        } catch (IOException e) {
            throw new CertificateCreationException("Error encountered when creating certificate", e);
        }
        if (log.isDebugEnabled()) {
            log.debug("Creates a self signed authentication certificate, fp="
                    + CertTools.getFingerprintAsString(certificate));
        }
    }
    // Add the credentials and new principal
    Set<X509Certificate> credentials = new HashSet<X509Certificate>();
    credentials.add(certificate);
    Set<X500Principal> principals = new HashSet<X500Principal>();
    principals.add(certificate.getSubjectX500Principal());

    // We cannot use the X509CertificateAuthenticationToken here, since it can only be used internally in a JVM.
    AuthenticationToken result = new TestX509CertificateAuthenticationToken(principals, credentials);
    return result;
}

From source file:com.eucalyptus.crypto.DefaultCryptoProvider.java

@Override
public X509Certificate generateCertificate(KeyPair keys, X500Principal subjectDn, X500Principal signer,
        PrivateKey signingKey, Date notAfter) {
    signer = (signingKey == null ? signer : subjectDn);
    signingKey = (signingKey == null ? keys.getPrivate() : signingKey);
    EventRecord.caller(DefaultCryptoProvider.class, EventType.GENERATE_CERTIFICATE, signer.toString(),
            subjectDn.toString()).info();
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setSerialNumber(BigInteger.valueOf(System.nanoTime()).shiftLeft(4)
            .add(BigInteger.valueOf((long) Math.rint(Math.random() * 1000))));
    certGen.setIssuerDN(signer);// w  w w.  j a v  a  2s .  c  o m
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
    try {
        certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
                new SubjectKeyIdentifierStructure(keys.getPublic()));
    } catch (InvalidKeyException e) {
        LOG.error("Error adding subject key identifier extension.", e);
    }
    Calendar cal = Calendar.getInstance();
    certGen.setNotBefore(cal.getTime());
    certGen.setNotAfter(notAfter);
    certGen.setSubjectDN(subjectDn);
    certGen.setPublicKey(keys.getPublic());
    certGen.setSignatureAlgorithm(KEY_SIGNING_ALGORITHM);
    try {
        X509Certificate cert = certGen.generate(signingKey, PROVIDER);
        cert.checkValidity();
        return cert;
    } catch (Exception e) {
        LOG.fatal(e, e);
        return null;
    }
}

From source file:org.apache.openaz.xacml.pdp.test.custom.TestCustom.java

/**
 * This function generates the public/private key pair. Should never have to call this again, this was
 * called once to generate the keys. They were saved into the testsets/custom/datatype-function
 * sub-directory./*ww  w  .ja v  a  2s.c  o  m*/
 */
public void generateKeyPair() {
    //
    // Generate a RSA private/public key pair
    //
    KeyPairGenerator keyGen;
    try {
        keyGen = KeyPairGenerator.getInstance(ALGORITHM);
    } catch (NoSuchAlgorithmException e) {
        logger.error("failed to generate keypair: " + e);
        return;
    }
    keyGen.initialize(1024);
    final KeyPair key = keyGen.generateKeyPair();
    //
    // Save the keys to disk
    //
    Path file = Paths.get(this.directory, PRIVATEKEY_FILE);
    try (ObjectOutputStream os = new ObjectOutputStream(Files.newOutputStream(file))) {
        os.writeObject(key.getPrivate());
    } catch (IOException e) {
        e.printStackTrace();
    }
    file = Paths.get(this.directory, PUBLICKEY_FILE);
    try (ObjectOutputStream os = new ObjectOutputStream(Files.newOutputStream(file))) {
        os.writeObject(key.getPublic());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:edu.vt.middleware.crypt.signature.SignatureAlgorithmTest.java

/**
 * @param  signature  A crypto signature algorithm to test.
 * @param  keys  Public/private key pair used for signing.
 * @param  converter  Converter used to convert sig bytes to String.
 *
 * @throws  Exception  On test failure./*from   ww  w  .  j  a v a 2  s  . com*/
 */
@Test(groups = { "functest", "signature" }, dataProvider = "testdata")
public void testSignVerifyOnStream(final SignatureAlgorithm signature, final KeyPair keys,
        final Converter converter) throws Exception {
    logger.info("Testing signature stream handling for " + signature + " with converter " + converter);

    final InputStream in1 = getClass().getResourceAsStream(BIG_FILE_PATH);
    final InputStream in2 = getClass().getResourceAsStream(BIG_FILE_PATH);
    try {
        signature.setRandomProvider(new SecureRandom());
        signature.setSignKey(keys.getPrivate());
        signature.initSign();
        if (converter == null) {
            final byte[] signedBytes = signature.sign(in1);
            signature.setVerifyKey(keys.getPublic());
            signature.initVerify();
            AssertJUnit.assertTrue(signature.verify(in2, signedBytes));
        } else {
            final String sig = signature.sign(in1, converter);
            signature.setVerifyKey(keys.getPublic());
            signature.initVerify();
            AssertJUnit.assertTrue(signature.verify(in2, sig, converter));
        }
    } finally {
        if (in1 != null) {
            in1.close();
        }
        if (in2 != null) {
            in2.close();
        }
    }
}

From source file:com.atlassian.jira.security.auth.trustedapps.DefaultCurrentApplicationStore.java

private Pair<KeyPair, CurrentApplication> getOrCreateCurrentApplication() {
    accessLock.lock();/*from  w  ww.j  av a2 s .  c  o m*/
    final KeyPair keyPair;
    String uid;
    try {
        final String privateKeyData = applicationProperties.getText(Keys.PRIVATE_KEY_DATA);
        final String publicKeyData = applicationProperties.getText(Keys.PUBLIC_KEY_DATA);

        if (isBlank(privateKeyData)) {
            keyPair = generateNewKeyPair();
            applicationProperties.setText(Keys.PRIVATE_KEY_DATA, KeyFactory.encode(keyPair.getPrivate()));
            applicationProperties.setText(Keys.PUBLIC_KEY_DATA, KeyFactory.encode(keyPair.getPublic()));
        } else {
            PrivateKey privateKey = KeyFactory.getPrivateKey(privateKeyData);
            PublicKey publicKey = KeyFactory.getPublicKey(publicKeyData);

            keyPair = new KeyPair(publicKey, privateKey);
        }

        uid = applicationProperties.getString(Keys.UID);
        if (isBlank(uid)) {
            uid = new UIDGenerator().generateUID(licenseService);
            applicationProperties.setString(Keys.UID, uid);
        }
    } finally {
        accessLock.unlock();
    }
    CurrentApplication application = new DefaultCurrentApplication(keyPair.getPublic(), keyPair.getPrivate(),
            uid);
    return Pair.of(keyPair, application);
}

From source file:com.subgraph.vega.internal.http.proxy.ssl.CertificateCreator.java

private HostCertificateData createCaSignedCertificateDataFor(X500Principal subject, KeyPair subjectKeys)
        throws CertificateException {
    final X509Certificate[] chain = new X509Certificate[2];
    chain[0] = generateCertificate(subject, subjectKeys.getPublic(), caSubject, caPublicKey, caPrivateKey,
            false);//from w  w w. j  a  va 2 s  .  co m
    chain[1] = caCertificate;
    return new HostCertificateData(subject.getName(), subjectKeys.getPrivate(), chain);
}

From source file:org.apache.hadoop.security.ssl.TestReloadingX509KeyManager.java

@Test(timeout = 4000)
public void testReloadMissingKeyStore() throws Exception {
    KeyPair keyPair = KeyStoreTestUtil.generateKeyPair(KEY_PAIR_ALGORITHM);
    X509Certificate cert = KeyStoreTestUtil.generateCertificate("CN=cert", keyPair, 2, CERTIFICATE_ALGORITHM);
    String keyStoreLocation = Paths.get(BASE_DIR, "testKeystore.jks").toString();
    KeyStoreTestUtil.createKeyStore(keyStoreLocation, KEYSTORE_PASSWORD, "cert", keyPair.getPrivate(), cert);

    ReloadingX509KeyManager keyManager = new ReloadingX509KeyManager("jks", keyStoreLocation, KEYSTORE_PASSWORD,
            KEYSTORE_PASSWORD, 10, TimeUnit.MILLISECONDS);
    try {/*from  w w  w.  ja va 2s  .c  om*/
        keyManager.init();
        X509Certificate[] certChain = keyManager.getCertificateChain("cert");
        assertNotNull("Certificate chain should not be null for alias cert", certChain);

        // Delete the keystore
        FileUtils.forceDelete(new File(keyStoreLocation));

        keyManager.getReloadTimeUnit().sleep(keyManager.getReloadInterval());
        TimeUnit.SECONDS.sleep(1);

        AtomicBoolean fileExists = keyManager.getFileExists();
        assertFalse("Key manager should detect file does not exist", fileExists.get());

        certChain = keyManager.getCertificateChain("cert");
        assertNotNull("Certificate chain should not be null for alias cert", certChain);
    } finally {
        keyManager.stop();
    }
}