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.atlassian.jira.security.auth.trustedapps.TestDefaultCurrentApplicationStore.java

@Test
public void testCreatesPropertiesIfNotThere() throws Exception {
    TrustedApplicationProperties properties = new TrustedApplicationProperties();

    DefaultCurrentApplicationStore factory = new DefaultCurrentApplicationStore(properties,
            stubServerId("THIS.ISNT.AREA.LSID"), new MemoryCacheManager(), new SimpleClusterLockService());

    factory.start();//from   w w w .  ja  va 2 s.  co  m
    final CurrentApplication currentApplication = factory.getCurrentApplication();
    assertNotNull(currentApplication);

    KeyPair newPair = properties.getPair();
    assertNotNull(newPair.getPrivate());
    assertNotNull(newPair.getPublic());
    assertTrue(isNotBlank(properties.getApplicationId()));

    assertState(newPair, properties.getApplicationId(), factory);
}

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

@Test(timeout = 4000)
public void testReloadCorruptedKeyStore() 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  v a2s  . c om
        keyManager.init();
        X509Certificate[] certChain = keyManager.getCertificateChain("cert");
        assertNotNull("Certificate chain should not be null for alias cert", certChain);

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

        FileOutputStream outputStream = new FileOutputStream(keyStoreLocation);
        outputStream.write("something".getBytes());
        outputStream.close();

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

        certChain = keyManager.getCertificateChain("cert");
        assertNotNull("Certificate chain should not be null for alias cert", certChain);
        assertEquals("DN for cert should be CN=cert", cert.getSubjectDN().getName(),
                certChain[0].getSubjectDN().getName());
        List<ScheduledFuture> reloadTasks = KeyManagersReloaderThreadPool.getInstance(true).getListOfTasks();
        // Reloading thread should have been cancelled after unsuccessful reload
        for (ScheduledFuture task : reloadTasks) {
            assertTrue(task.isCancelled());
        }
        assertEquals(KeyManagersReloaderThreadPool.MAX_NUMBER_OF_RETRIES + 1, keyManager.getNumberOfFailures());
    } finally {
        keyManager.stop();
    }
}

From source file:com.streamsets.datacollector.publicrestapi.TestCredentialsDeploymentResource.java

@Test
public void testSuccess() throws Exception {
    Properties sdcProps = new Properties();
    sdcProps.setProperty("a", "b");
    sdcProps.setProperty("c", "d");
    sdcProps.setProperty("kerberos.client.keytab", "sdc.keytab");
    sdcProps.setProperty("kerberos.client.enabled", "false");
    sdcProps.setProperty("kerberos.client.principal", "sdc/_HOST@EXAMPLE.COM");
    File sdcFile = new File(RuntimeInfoTestInjector.confDir, "sdc.properties");

    Properties dpmProps = new Properties();
    dpmProps.setProperty("x", "y");
    dpmProps.setProperty("z", "a");
    dpmProps.setProperty("dpm.enabled", "false");
    dpmProps.setProperty("dpm.base.url", "http://localhost:18631");
    File dpmFile = new File(RuntimeInfoTestInjector.confDir, "dpm.properties");

    try (FileWriter fw = new FileWriter(sdcFile)) {
        sdcProps.store(fw, "");
    }/*from  ww  w.j a v  a 2s.co  m*/

    try (FileWriter fw = new FileWriter(dpmFile)) {
        dpmProps.store(fw, "");
    }

    Response response = null;
    KeyPair keys = generateKeys();
    mockCheckForCredentialsRequiredToTrue();
    System.setProperty(DPM_AGENT_PUBLIC_KEY, Base64.getEncoder().encodeToString(keys.getPublic().getEncoded()));
    String token = "Frenchies and Pandas";
    Signature sig = Signature.getInstance("SHA256withRSA");
    sig.initSign(keys.getPrivate());
    sig.update(token.getBytes(Charsets.UTF_8));
    List<String> labels = Arrays.asList("deployment-prod-1", "deployment-prod-2");
    CredentialsBeanJson json = new CredentialsBeanJson(token, "streamsets/172.1.1.0@EXAMPLE.COM",
            Base64.getEncoder().encodeToString("testKeytab".getBytes(Charsets.UTF_8)),
            Base64.getEncoder().encodeToString(sig.sign()), "https://dpm.streamsets.com:18631",
            Arrays.asList("deployment-prod-1", "deployment-prod-2"), "deployment1:org");

    try {
        response = target("/v1/deployment/deployCredentials").request().post(Entity.json(json));
        Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
        CredentialDeploymentResponseJson responseJson = OBJECT_MAPPER
                .readValue((InputStream) response.getEntity(), CredentialDeploymentResponseJson.class);
        Assert.assertEquals(CredentialDeploymentStatus.CREDENTIAL_USED_AND_DEPLOYED,
                responseJson.getCredentialDeploymentStatus());

        // Verify sdc.properties
        sdcProps = new Properties();
        try (FileReader fr = new FileReader(sdcFile)) {
            sdcProps.load(fr);
        }
        Assert.assertEquals("b", sdcProps.getProperty("a"));
        Assert.assertEquals("d", sdcProps.getProperty("c"));
        Assert.assertEquals("streamsets/172.1.1.0@EXAMPLE.COM",
                sdcProps.getProperty("kerberos.client.principal"));
        Assert.assertEquals("true", sdcProps.getProperty("kerberos.client.enabled"));
        Assert.assertEquals("sdc.keytab", sdcProps.getProperty("kerberos.client.keytab"));
        byte[] keyTab = Files.toByteArray(new File(RuntimeInfoTestInjector.confDir, "sdc.keytab"));
        Assert.assertEquals("testKeytab", new String(keyTab, Charsets.UTF_8));
        response = target("/v1/definitions").request().get();
        Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());

        dpmProps = new Properties();
        try (FileReader fr = new FileReader(dpmFile)) {
            dpmProps.load(fr);
        }
        Assert.assertEquals("y", dpmProps.getProperty("x"));
        Assert.assertEquals("a", dpmProps.getProperty("z"));
        Assert.assertEquals("true", dpmProps.getProperty("dpm.enabled"));
        Assert.assertEquals(
                Configuration.FileRef.PREFIX + "application-token.txt" + Configuration.FileRef.SUFFIX,
                dpmProps.getProperty("dpm.appAuthToken"));
        Assert.assertEquals("https://dpm.streamsets.com:18631", dpmProps.getProperty("dpm.base.url"));

        Assert.assertEquals(StringUtils.join(labels.toArray(), ","),
                dpmProps.getProperty(RemoteEventHandlerTask.REMOTE_JOB_LABELS));
        Assert.assertEquals("deployment1:org", dpmProps.getProperty(RemoteSSOService.DPM_DEPLOYMENT_ID));

        File tokenFile = new File(RuntimeInfoTestInjector.confDir, "application-token.txt");
        try (FileInputStream fr = new FileInputStream(tokenFile)) {
            int len = token.length();
            byte[] tokenBytes = new byte[len];
            Assert.assertEquals(len, fr.read(tokenBytes));
            Assert.assertEquals(token, new String(tokenBytes, Charsets.UTF_8));
        }
        //Test redeploying the credentials again
        response = target("/v1/deployment/deployCredentials").request().post(Entity.json(json));
        responseJson = OBJECT_MAPPER.readValue((InputStream) response.getEntity(),
                CredentialDeploymentResponseJson.class);
        Assert.assertEquals(CredentialDeploymentStatus.CREDENTIAL_NOT_USED_ALREADY_DEPLOYED,
                responseJson.getCredentialDeploymentStatus());

    } finally {
        if (response != null) {
            response.close();
        }
    }
}

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

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

    ReloadingX509KeyManager keyManager = new ReloadingX509KeyManager("jks", keyStoreLocation, KEYSTORE_PASSWORD,
            KEYSTORE_PASSWORD, 10, TimeUnit.MILLISECONDS);

    try {/*from w  w w .  ja v a2s. c  om*/
        keyManager.init();

        TimeUnit reloadTimeUnit = keyManager.getReloadTimeUnit();
        long reloadInterval = keyManager.getReloadInterval();

        X509Certificate[] certChain = keyManager.getCertificateChain("cert1");
        assertNotNull("Certificate chain should not be null for alias cert1", certChain);
        assertEquals("Certificate chain should be 1", 1, certChain.length);
        assertEquals("DN for cert1 should be CN=cert1", cert1.getSubjectDN().getName(),
                certChain[0].getSubjectDN().getName());

        // Wait a bit for the modification time to be different
        reloadTimeUnit.sleep(reloadInterval);
        TimeUnit.SECONDS.sleep(1);

        // Replace keystore with a new one with a different DN
        X509Certificate cert2 = KeyStoreTestUtil.generateCertificate("CN=cert2", keyPair, 2,
                CERTIFICATE_ALGORITHM);
        KeyStoreTestUtil.createKeyStore(keyStoreLocation, KEYSTORE_PASSWORD, "cert2", keyPair.getPrivate(),
                cert2);

        reloadTimeUnit.sleep(reloadInterval * 2);

        certChain = keyManager.getCertificateChain("cert1");
        assertNull("Certificate chain for alias cert1 should be null", certChain);
        certChain = keyManager.getCertificateChain("cert2");
        assertNotNull("Certificate chain should not be null for alias cert2", certChain);
        assertEquals("Certificate chain should be 1", 1, certChain.length);
        assertEquals("DN for cert2 should be CN=cert2", cert2.getSubjectDN().getName(),
                certChain[0].getSubjectDN().getName());

    } finally {
        keyManager.stop();
    }
}

From source file:org.bedework.util.security.pki.PKITools.java

/**
 * @return RSAKeys//from ww  w . j  a v a 2  s. co m
 * @throws PKIException
 */
public RSAKeys genRSAKeys() throws PKIException {
    RSAKeys keys = new RSAKeys();

    try {
        SecureRandom secureRandom = new SecureRandom();
        secureRandom.nextBytes(new byte[1]);
        KeyPairGenerator rsaKeyGen;

        if (curSchema.pName == null) {
            rsaKeyGen = KeyPairGenerator.getInstance(curSchema.keyFactory);
        } else {
            rsaKeyGen = KeyPairGenerator.getInstance(curSchema.keyFactory, curSchema.pName);
        }

        rsaKeyGen.initialize(1024, secureRandom);

        if (trace()) {
            trace("Generating keys...");
        }

        KeyPair rsaKeyPair = rsaKeyGen.generateKeyPair();

        if (trace()) {
            trace("Saving Public Key...");
        }

        keys.privateKey = rsaKeyPair.getPrivate().getEncoded();
        keys.publicKey = rsaKeyPair.getPublic().getEncoded();

        if (trace()) {
            trace("Done...");
        }

        return keys;
    } catch (Throwable t) {
        throw new PKIException(t);
    }
}

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

@Test
public void testReloadWithPasswordfile() throws Exception {
    KeyPair keyPair = KeyStoreTestUtil.generateKeyPair(KEY_PAIR_ALGORITHM);
    X509Certificate cert1 = KeyStoreTestUtil.generateCertificate("CN=cert1", keyPair, 2, CERTIFICATE_ALGORITHM);

    String keyStoreLocation = Paths.get(BASE_DIR, "testKeystore.jks").toString();
    KeyStoreTestUtil.createKeyStore(keyStoreLocation, KEYSTORE_PASSWORD, "cert1", keyPair.getPrivate(), cert1);

    String passwordFileLocation = Paths.get(BASE_DIR, "password_file").toString();
    FileUtils.write(new File(passwordFileLocation), KEYSTORE_PASSWORD);

    ReloadingX509KeyManager keyManager = new ReloadingX509KeyManager("jks", keyStoreLocation, "wrong-password",
            passwordFileLocation, "wrong-password", 10, TimeUnit.MILLISECONDS);

    try {//from   w ww  .  ja  v  a2 s  . com
        keyManager.init();

        TimeUnit reloadTimeUnit = keyManager.getReloadTimeUnit();
        long reloadInterval = keyManager.getReloadInterval();

        X509Certificate[] certChain = keyManager.getCertificateChain("cert1");
        assertNotNull("Certificate chain should not be null for alias cert1", certChain);
        assertEquals("Certificate chain should be 1", 1, certChain.length);
        assertEquals("DN for cert1 should be CN=cert1", cert1.getSubjectDN().getName(),
                certChain[0].getSubjectDN().getName());

        // Wait a bit for the modification time to be different
        reloadTimeUnit.sleep(reloadInterval);
        TimeUnit.SECONDS.sleep(1);

        // Replace keystore with a new one with a different DN
        X509Certificate cert2 = KeyStoreTestUtil.generateCertificate("CN=cert2", keyPair, 2,
                CERTIFICATE_ALGORITHM);
        String newKeystorePassword = "password1";
        KeyStoreTestUtil.createKeyStore(keyStoreLocation, newKeystorePassword, "cert2", keyPair.getPrivate(),
                cert2);
        FileUtils.write(new File(passwordFileLocation), newKeystorePassword);

        reloadTimeUnit.sleep(reloadInterval * 2);

        certChain = keyManager.getCertificateChain("cert1");
        assertNull("Certificate chain for alias cert1 should be null", certChain);
        certChain = keyManager.getCertificateChain("cert2");
        assertNotNull("Certificate chain should not be null for alias cert2", certChain);
        assertEquals("Certificate chain should be 1", 1, certChain.length);
        assertEquals("DN for cert2 should be CN=cert2", cert2.getSubjectDN().getName(),
                certChain[0].getSubjectDN().getName());

    } finally {
        keyManager.stop();
    }
}

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

protected List<Path> prepareCryptoMaterial(Configuration conf, String outDir) throws Exception {
    List<Path> filesToPurge = new ArrayList<>();
    this.outDir = outDir;

    String keyAlg = "RSA";
    String signAlg = "SHA256withRSA";

    // Generate CA
    KeyPair caKeyPair = KeyStoreTestUtil.generateKeyPair(keyAlg);
    X509Certificate caCert = KeyStoreTestUtil.generateCertificate("CN=CARoot", caKeyPair, 42, signAlg);

    // Generate server certificate signed by CA
    KeyPair serverKeyPair = KeyStoreTestUtil.generateKeyPair(keyAlg);
    X509Certificate serverCrt = KeyStoreTestUtil.generateSignedCertificate("CN=serverCrt", serverKeyPair, 42,
            signAlg, caKeyPair.getPrivate(), caCert);

    serverKeyStore = Paths.get(outDir, "server.keystore.jks");
    serverTrustStore = Paths.get(outDir, "server.truststore.jks");
    filesToPurge.add(serverKeyStore);/*from   w  w  w  . jav  a  2  s.c om*/
    filesToPurge.add(serverTrustStore);
    KeyStoreTestUtil.createKeyStore(serverKeyStore.toString(), passwd, passwd, "server_alias",
            serverKeyPair.getPrivate(), serverCrt);
    KeyStoreTestUtil.createTrustStore(serverTrustStore.toString(), passwd, "CARoot", caCert);

    // Generate client certificate with the correct CN field and signed by the CA
    KeyPair c_clientKeyPair = KeyStoreTestUtil.generateKeyPair(keyAlg);
    String c_cn = "CN=" + UserGroupInformation.getCurrentUser().getUserName();
    X509Certificate c_clientCrt = KeyStoreTestUtil.generateSignedCertificate(c_cn, c_clientKeyPair, 42, signAlg,
            caKeyPair.getPrivate(), caCert);

    c_clientKeyStore = Paths.get(outDir, "c_client.keystore.jks");
    c_clientTrustStore = Paths.get(outDir, "c_client.truststore.jks");
    filesToPurge.add(c_clientKeyStore);
    filesToPurge.add(c_clientTrustStore);
    KeyStoreTestUtil.createKeyStore(c_clientKeyStore.toString(), passwd, passwd, "c_client_alias",
            c_clientKeyPair.getPrivate(), c_clientCrt);
    KeyStoreTestUtil.createTrustStore(c_clientTrustStore.toString(), passwd, "CARoot", caCert);

    if (error_mode.equals(CERT_ERR.NO_CA)) {
        LOG.info("no ca error mode");
        // Generate client certificate with the correct CN field but NOT signed by the CA
        KeyPair noCA_clientKeyPair = KeyStoreTestUtil.generateKeyPair(keyAlg);
        X509Certificate noCA_clientCrt = KeyStoreTestUtil.generateCertificate(c_cn, noCA_clientKeyPair, 42,
                signAlg);

        err_clientKeyStore = Paths.get(outDir, "noCA_client.keystore.jks");
        err_clientTrustStore = Paths.get(outDir, "noCA_client.truststore.jks");
        filesToPurge.add(err_clientKeyStore);
        filesToPurge.add(err_clientTrustStore);
        KeyStoreTestUtil.createKeyStore(err_clientKeyStore.toString(), passwd, passwd, "noca_client_alias",
                noCA_clientKeyPair.getPrivate(), noCA_clientCrt);
        KeyStoreTestUtil.createTrustStore(err_clientTrustStore.toString(), passwd, "CARoot", caCert);

    } else if (error_mode.equals(CERT_ERR.ERR_CN)) {
        LOG.info("wrong cn error mode");
        // Generate client with INCORRECT CN field but signed by the CA
        KeyPair errCN_clientKeyPair = KeyStoreTestUtil.generateKeyPair(keyAlg);
        X509Certificate errCN_clientCrt = KeyStoreTestUtil.generateSignedCertificate("CN=Phil Lynott",
                errCN_clientKeyPair, 42, signAlg, caKeyPair.getPrivate(), caCert);

        err_clientKeyStore = Paths.get(outDir, "errCN_client.keystore.jks");
        err_clientTrustStore = Paths.get(outDir, "errCN_client.truststore.jks");
        filesToPurge.add(err_clientKeyStore);
        filesToPurge.add(err_clientTrustStore);
        KeyStoreTestUtil.createKeyStore(err_clientKeyStore.toString(), passwd, passwd, "errcn_client_alias",
                errCN_clientKeyPair.getPrivate(), errCN_clientCrt);
        KeyStoreTestUtil.createTrustStore(err_clientTrustStore.toString(), passwd, "CARoot", caCert);
    }

    return filesToPurge;
}

From source file:cloud.google.com.windows.example.ExampleCode.java

private String decryptPassword(String message, KeyPair keys) {
    try {/*from w  w w  .  ja  v  a2  s  .c om*/
        // Add the bouncycastle provider - the built-in providers don't support RSA
        // with OAEPPadding.
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

        // Get the appropriate cipher instance.
        Cipher rsa = Cipher.getInstance("RSA/NONE/OAEPPadding", "BC");

        // Add the private key for decryption.
        rsa.init(Cipher.DECRYPT_MODE, keys.getPrivate());

        // Decrypt the text.
        byte[] rawMessage = Base64.decodeBase64(message);
        byte[] decryptedText = rsa.doFinal(rawMessage);

        // The password was encoded using UTF8. Transform into string.
        return new String(decryptedText, "UTF8");
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
    return "";
}

From source file:org.mitre.jwt.signer.impl.RsaSigner.java

/**
 * Load the public and private keys from the keystore, identified with the configured alias and accessed with the configured password.
 * @throws GeneralSecurityException// w w  w . j  av  a2s.c om
 */
private void loadKeysFromKeystore() {
    Assert.notNull(keystore, "An keystore must be supplied");
    Assert.notNull(alias, "A alias must be supplied");
    Assert.notNull(password, "A password must be supplied");

    KeyPair keyPair = null;
    try {
        keyPair = keystore.getKeyPairForAlias(alias, password);
    } catch (GeneralSecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Assert.notNull(keyPair, "Either alias and/or password is not correct for keystore");

    publicKey = keyPair.getPublic();
    privateKey = keyPair.getPrivate();
}

From source file:test.integ.be.fedict.hsm.ws.WebServiceSecurityTest.java

@Test
public void testWSSecurityClientWSSecurity() throws Exception {
    DigitalSignatureServicePortType dssPort = getPort();

    KeyPair keyPair = HSMProxyTestCredential.generateKeyPair();
    X509Certificate certificate = HSMProxyTestCredential.generateSelfSignedCertificate(keyPair);

    be.fedict.hsm.client.WSSecuritySOAPHandler securityTestSOAPHandler = new be.fedict.hsm.client.WSSecuritySOAPHandler(
            keyPair.getPrivate(), certificate);
    addSOAPHandler(securityTestSOAPHandler, dssPort);

    ObjectFactory objectFactory = new ObjectFactory();
    SignRequest signRequest = objectFactory.createSignRequest();

    dssPort.sign(signRequest);/*from   www  . j av a  2 s. c o m*/
}