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:eu.contrail.security.DelegatedUserCertClientTest.java

public void testGetDelegatedUserCertWithStorePass() throws Exception {

    System.out.println("getDelegatedUserCert WITH server pass");

    /*/*ww  w  .  j a  va  2  s  . c o m*/
     * If the propsFile property isn't set, read the properties files from a hard-wired locationn
     * 
     */

    String propsFile = System.getProperty("propsFile", "./src/test/resources/ucstest.properties");

    Properties props = null;

    try {

        props = new Properties();
        props.load(new FileInputStream(propsFile));

    } catch (Exception ex) {
        System.err.println(ex);
    }

    //    System.setProperty("javax.net.debug", "ssl");

    /*
     * If the targetUrl property isn't set, use a hard-wired URL
     * 
     */
    String uriSpec = "https://one-test.contrail.rl.ac.uk:8443/ca/delegateduser";

    KeyPair keyPair = sc.generateKeyPair("RSA", 2048);

    String signatureAlgorithm = "SHA256withRSA";

    /*
     * Use a well-known username/password combination
     * 
     */

    //    System.setProperty("javax.net.debug", "ssl");

    String proxyHost = null;
    String proxyPortSpec = null;
    String proxyScheme = null;
    DelegatedCertClient instance = new DelegatedCertClient(uriSpec, true,
            "./src/test/resources/cloud052.gridpp.rl.ac.uk-keystore.p12" /* lcg0710.gridpp.rl.ac.uk-keystore.p12" */,
            "client",
            //      "/Library/Java/Home/lib/security/cacerts", "changeit");

            "./src/test/resources/caserver.jks", "caserver");

    /* Can use either the CA certs file, or a truststore containing the actual server SSL cert */
    /* Should test using a TERENA CA cert on its own? */

    X509Certificate result = null;

    String userID = "3";

    try {
        System.out.printf("Calling %s.%n", uriSpec);

        result = instance.getCert(keyPair, signatureAlgorithm, userID, true);

        if (result == null) {

            throw new Exception(); // Throw an Exception to signal test has failed

        }

        System.out.println("Delegated User Private Key:");
        sc.writeKey(System.out, keyPair.getPrivate());

        System.out.println("\nDelegated User Certificate from CA Server:");

        sc.writeCertificate(System.out, result);

    } catch (IllegalArgumentException ex) {

        System.err.printf(ex.getLocalizedMessage());

    }

}

From source file:org.ejbca.core.protocol.scep.ProtocolScepHttpTest.java

private byte[] genScepRequest(boolean makeCrlReq, String digestoid, String userDN, KeyPair keyPair,
        String signatureProvider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException,
        SignatureException, InvalidAlgorithmParameterException, CertStoreException, IOException, CMSException,
        OperatorCreationException, CertificateException {
    ScepRequestGenerator gen = new ScepRequestGenerator();
    gen.setKeys(keyPair, signatureProvider);
    gen.setDigestOid(digestoid);/*from  w w  w .  j  ava  2s. com*/
    byte[] msgBytes = null;
    // Create a transactionId
    byte[] randBytes = new byte[16];
    this.rand.nextBytes(randBytes);
    byte[] digest = CertTools.generateMD5Fingerprint(randBytes);
    transId = new String(Base64.encode(digest));
    final X509Certificate senderCertificate = CertTools.genSelfCert("CN=SenderCertificate", 24 * 60 * 60 * 1000,
            null, keyPair.getPrivate(), keyPair.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, false);
    if (makeCrlReq) {
        msgBytes = gen.generateCrlReq(userDN, transId, cacert, senderCertificate, keyPair.getPrivate());
    } else {
        msgBytes = gen.generateCertReq(userDN, "foo123", transId, cacert, senderCertificate,
                keyPair.getPrivate());
    }
    assertNotNull(msgBytes);
    senderNonce = gen.getSenderNonce();
    byte[] nonceBytes = Base64.decode(senderNonce.getBytes());
    assertTrue(nonceBytes.length == 16);
    return msgBytes;
}

From source file:net.maritimecloud.identityregistry.utils.CertificateUtil.java

/**
 * Generates a self-signed certificate based on the keypair and saves it in the keystore.
 * Should only be used to init the CA./*www.j ava2 s. c o m*/
 */
public void initCA(String rootCertX500Name, String mcidregCertX500Name, String crlUrl, String ocspUrl,
        String outputCaCrlPath) {
    if (KEYSTORE_PASSWORD == null) {
        KEYSTORE_PASSWORD = "changeit";
    }
    if (ROOT_KEYSTORE_PATH == null) {
        ROOT_KEYSTORE_PATH = "mc-root-keystore.jks";
    }
    if (INTERMEDIATE_KEYSTORE_PATH == null) {
        INTERMEDIATE_KEYSTORE_PATH = "mc-it-keystore.jks";
    }
    if (TRUSTSTORE_PASSWORD == null) {
        TRUSTSTORE_PASSWORD = "changeit";
    }
    if (TRUSTSTORE_PATH == null) {
        TRUSTSTORE_PATH = "mc-truststore.jks";
    }
    if (CRL_URL == null) {
        CRL_URL = crlUrl;
    }
    if (OCSP_URL == null) {
        OCSP_URL = ocspUrl;
    }
    KeyPair cakp = generateKeyPair();
    KeyPair imkp = generateKeyPair();
    KeyStore rootks = null;
    KeyStore itks;
    KeyStore ts;
    FileOutputStream rootfos = null;
    FileOutputStream itfos = null;
    FileOutputStream tsfos = null;
    try {
        rootks = KeyStore.getInstance(KEYSTORE_TYPE); // KeyStore.getDefaultType() 
        rootks.load(null, KEYSTORE_PASSWORD.toCharArray());
        itks = KeyStore.getInstance(KEYSTORE_TYPE); // KeyStore.getDefaultType() 
        itks.load(null, KEYSTORE_PASSWORD.toCharArray());
        // Store away the keystore.
        rootfos = new FileOutputStream(ROOT_KEYSTORE_PATH);
        itfos = new FileOutputStream(INTERMEDIATE_KEYSTORE_PATH);
        X509Certificate cacert;
        try {
            cacert = buildAndSignCert(generateSerialNumber(), cakp.getPrivate(), cakp.getPublic(),
                    cakp.getPublic(), new X500Name(rootCertX500Name), new X500Name(rootCertX500Name), null,
                    "ROOTCA");
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        X509Certificate imcert;
        try {
            imcert = buildAndSignCert(generateSerialNumber(), cakp.getPrivate(), cakp.getPublic(),
                    imkp.getPublic(), new X500Name(rootCertX500Name), new X500Name(mcidregCertX500Name), null,
                    "INTERMEDIATE");
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        Certificate[] certChain = new Certificate[1];
        certChain[0] = cacert;
        rootks.setKeyEntry(ROOT_CERT_ALIAS, cakp.getPrivate(), KEYSTORE_PASSWORD.toCharArray(), certChain);
        rootks.store(rootfos, KEYSTORE_PASSWORD.toCharArray());
        rootks = KeyStore.getInstance(KeyStore.getDefaultType());
        rootks.load(null, KEYSTORE_PASSWORD.toCharArray());

        certChain = new Certificate[2];
        certChain[0] = imcert;
        certChain[1] = cacert;
        itks.setKeyEntry(INTERMEDIATE_CERT_ALIAS, imkp.getPrivate(), KEYSTORE_PASSWORD.toCharArray(),
                certChain);
        itks.store(itfos, KEYSTORE_PASSWORD.toCharArray());

        // Store away the truststore.
        ts = KeyStore.getInstance(KeyStore.getDefaultType());
        ts.load(null, TRUSTSTORE_PASSWORD.toCharArray());
        tsfos = new FileOutputStream(TRUSTSTORE_PATH);
        ts.setCertificateEntry(ROOT_CERT_ALIAS, cacert);
        ts.setCertificateEntry(INTERMEDIATE_CERT_ALIAS, imcert);
        ts.store(tsfos, TRUSTSTORE_PASSWORD.toCharArray());
    } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        safeClose(rootfos);
        safeClose(itfos);
        safeClose(tsfos);

        KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection(
                KEYSTORE_PASSWORD.toCharArray());
        PrivateKeyEntry rootCertEntry;
        try {
            rootCertEntry = (PrivateKeyEntry) rootks.getEntry(ROOT_CERT_ALIAS, protParam);
            generateRootCACRL(rootCertX500Name, null, rootCertEntry, outputCaCrlPath);
        } catch (NoSuchAlgorithmException | UnrecoverableEntryException | KeyStoreException e) {
            // todo, I think is an irrecoverable state, but we should not throw exception from finally, perhaps this code should not be in a finally block
            log.error("unable to generate RootCACRL", e);
        }

    }
}

From source file:org.cesecore.certificates.ca.X509CA.java

/**
 * @see CA#createRequest(Collection, String, Certificate, int)
 *///from w w w.j av a  2 s  . c o m
@Override
public byte[] createRequest(CryptoToken cryptoToken, Collection<ASN1Encodable> attributes, String signAlg,
        Certificate cacert, int signatureKeyPurpose) throws CryptoTokenOfflineException {
    log.trace(
            ">createRequest: " + signAlg + ", " + CertTools.getSubjectDN(cacert) + ", " + signatureKeyPurpose);
    ASN1Set attrset = new DERSet();
    if (attributes != null) {
        log.debug("Adding attributes in the request");
        Iterator<ASN1Encodable> iter = attributes.iterator();
        ASN1EncodableVector vec = new ASN1EncodableVector();
        while (iter.hasNext()) {
            ASN1Encodable o = (ASN1Encodable) iter.next();
            vec.add(o);
        }
        attrset = new DERSet(vec);
    }
    final X500NameStyle nameStyle;
    if (getUsePrintableStringSubjectDN()) {
        nameStyle = PrintableStringNameStyle.INSTANCE;
    } else {
        nameStyle = CeSecoreNameStyle.INSTANCE;
    }
    X500Name x509dn = CertTools.stringToBcX500Name(getSubjectDN(), nameStyle, getUseLdapDNOrder());
    PKCS10CertificationRequest req;
    try {
        final CAToken catoken = getCAToken();
        final String alias = catoken.getAliasFromPurpose(signatureKeyPurpose);
        final KeyPair keyPair = new KeyPair(cryptoToken.getPublicKey(alias), cryptoToken.getPrivateKey(alias));
        req = CertTools.genPKCS10CertificationRequest(signAlg, x509dn, keyPair.getPublic(), attrset,
                keyPair.getPrivate(), cryptoToken.getSignProviderName());
        log.trace("<createRequest");
        return req.getEncoded();
    } catch (CryptoTokenOfflineException e) { // NOPMD, since we catch wide below
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:duthientan.mmanm.com.Main.java

private void BntGenerationKeyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BntGenerationKeyActionPerformed
    // TODO add your handling code here:
    if (filePath.size() != 0) {

        progressBarCipher.setIndeterminate(true);
        new Thread(new Runnable() {
            @Override//from  ww w  .  ja va2 s .  c  o m
            public void run() {
                try {
                    Path path = Paths.get(filePath.get(0));
                    String srcParent = path.getParent().toString();
                    final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
                    keyGen.initialize(2048);
                    final KeyPair key = keyGen.generateKeyPair();
                    File privateKeyFile = new File(srcParent + "/private.key");
                    File publicKeyFile = new File(srcParent + "/public.key");
                    publicKeyFile.createNewFile();
                    publicKeyFile.createNewFile();
                    ObjectOutputStream publicKeyOS = new ObjectOutputStream(
                            new FileOutputStream(publicKeyFile));
                    publicKeyOS.writeObject(key.getPublic());
                    publicKeyOS.close();
                    ObjectOutputStream privateKeyOS = new ObjectOutputStream(
                            new FileOutputStream(privateKeyFile));
                    privateKeyOS.writeObject(key.getPrivate());
                    privateKeyOS.close();
                    progressBarCipher.setIndeterminate(false);
                    JFrame frame = new JFrame("COMPLETED");
                    JOptionPane.showMessageDialog(frame, "Greneration Key File Completed");
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                } catch (NoSuchAlgorithmException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }).start();

    } else {
        JFrame frame = new JFrame("ERROR");
        JOptionPane.showMessageDialog(frame, "Please Choice File To Cipher Before Greneration Key");
    }
}

From source file:edu.stanford.mobisocial.dungbeetle.DBHelper.java

private void generateAndStorePersonalInfo(SQLiteDatabase db) {
    String email = getUserEmail();
    String name = email; // How to get this?

    KeyPair keypair = DBIdentityProvider.generateKeyPair();
    PrivateKey privateKey = keypair.getPrivate();
    PublicKey publicKey = keypair.getPublic();
    String pubKeyStr = FastBase64.encodeToString(publicKey.getEncoded());
    String privKeyStr = FastBase64.encodeToString(privateKey.getEncoded());
    ContentValues cv = new ContentValues();
    cv.put(MyInfo.PUBLIC_KEY, pubKeyStr);
    cv.put(MyInfo.PRIVATE_KEY, privKeyStr);
    cv.put(MyInfo.NAME, name);/*ww w .  j  a va  2  s .  com*/
    cv.put(MyInfo.EMAIL, email);
    db.insertOrThrow(MyInfo.TABLE, null, cv);
    Log.d(TAG, "Generated public key: " + pubKeyStr);
    Log.d(TAG, "Generated priv key: **************");
}

From source file:org.ejbca.core.protocol.cmp.CrmfKeyUpdateTest.java

/**
 * Sends a KeyUpdateRequest concerning a certificate that does not exist in the database. A CMP error message is expected and no certificate renewal.
 * //  ww  w .ja v a2  s  . co m
 * - Pre-configuration: Sets the operational mode to client mode (cmp.raoperationalmode=normal)
 * - Pre-configuration: Sets cmp.allowautomaticrenewal to 'true' and tests that the resetting of configuration has worked.
 * - Pre-configuration: Sets cmp.allowupdatewithsamekey to 'true'
 * - Generates a self-signed certificate, fakecert
 * - Generates a CMP KeyUpdate Request and tests that such request has been created.
 * - Signs the CMP request using fakecert and attaches fakecert to the CMP request. Tests that the CMP request is still not null
 * - Sends the request using HTTP and receives an response.
 * - Examines the response:
 *       - Checks that the response is not empty or null
 *       - Checks that the protection algorithm is sha1WithRSAEncryption
 *       - Checks that the signer is the expected CA
 *       - Verifies the response signature
 *       - Checks that the response's senderNonce is 16 bytes long
 *       - Checks that the request's senderNonce is the same as the response's recipientNonce
 *       - Checks that the request and the response has the same transactionID
 *       - Parses the response and checks that the parsing did not result in a 'null'
 *       - Checks that the CMP response message tag number is '23', indicating a CMP error message
 *       - Checks that the CMP response message contain the expected error details text
 * 
 * @throws Exception
 */
@Test
public void test04UpdateKeyWithFakeCert() throws Exception {
    if (log.isTraceEnabled()) {
        log.trace(">test04UpdateKeyWithFakeCert");
    }

    this.cmpConfiguration.setKurAllowAutomaticUpdate(this.cmpAlias, true);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    //--------------- create the user and issue his first certificate -----------------
    final String fakeUsername = "fakeuser";
    final X500Name fakeUserDN = new X500Name("CN=" + fakeUsername + ",C=SE");
    createUser(fakeUsername, fakeUserDN.toString(), "foo123");

    KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    Certificate fakeCert = CertTools.genSelfCert(fakeUserDN.toString(), 30, null, keys.getPrivate(),
            keys.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, false);
    assertNotNull("Failed to create a test certificate", fakeCert);

    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);

    // Sending a request with a certificate that neither it nor the issuer CA is in the database
    PKIMessage req = genRenewalReq(this.userDN, this.cacert, this.nonce, this.transid, keys, false, null, null,
            pAlg, new DEROctetString(this.nonce));
    assertNotNull("Failed to generate a CMP renewal request", req);

    CMPCertificate[] extraCert = getCMPCert(fakeCert);
    req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, keys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");
    assertNotNull(req);

    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);
    byte[] ba = bao.toByteArray();
    // Send request and receive response
    byte[] resp = sendCmpHttp(ba, 200, this.cmpAlias);
    checkCmpResponseGeneral(resp, this.issuerDN, this.userDN, this.cacert, this.nonce, this.transid, false,
            null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());

    PKIMessage respObject = null;
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    assertNotNull(respObject);

    PKIBody body = respObject.getBody();
    assertEquals(23, body.getType());
    ErrorMsgContent err = (ErrorMsgContent) body.getContent();
    String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
    String expectedErrMsg = "The certificate attached to the PKIMessage in the extraCert field could not be found in the database.";
    assertEquals(expectedErrMsg, errMsg);

    // sending another renewal request with a certificate issued by an existing CA but the certificate itself is not in the database        
    // A certificate, not in the database, issued by TestCA
    byte[] fakecertBytes = Base64.decode(("MIIB6TCCAVKgAwIBAgIIIKF3bEBbbyQwDQYJKoZIhvcNAQELBQAwETEPMA0GA1UE"
            + "AwwGVGVzdENBMB4XDTEzMDMxMjExMTcyMVoXDTEzMDMyMjExMjcyMFowIDERMA8G"
            + "A1UEAwwIZmFrZXVzZXIxCzAJBgNVBAYTAlNFMFwwDQYJKoZIhvcNAQEBBQADSwAw"
            + "SAJBAKZlXrI3TwziiDK9/E1V4n6PCXhpRERSLWPEpRvRPWfpvazpq7R2UZZRq5i2"
            + "hrqKDbfLdAouh2J7AIlUZG3cdJECAwEAAaN/MH0wHQYDVR0OBBYEFCb2tsZTXOh7"
            + "FjjVXpSxkJ79P3tJMAwGA1UdEwEB/wQCMAAwHwYDVR0jBBgwFoAURmtK3gFt81Bp"
            + "3z+YZuzBm65Ja6IwDgYDVR0PAQH/BAQDAgXgMB0GA1UdJQQWMBQGCCsGAQUFBwMC"
            + "BggrBgEFBQcDBDANBgkqhkiG9w0BAQsFAAOBgQAmclw6cwuQkiPSN4bHOP5S7bdU"
            + "+UKXLIkk1L84q0WQfblNzYkcDXMsxwJ1dv2Yd/dxIjtVjrhVIUrRMA70jtWs31CH"
            + "t9ofdgncIdtzZo49mLRQDwhTCApoLf0BCNb2rWpzCPWQTa97y0u5T65m7DAkBTV/" + "JAkFQIZCLSAci++qPA==")
                    .getBytes());
    fakeCert = CertTools.getCertfromByteArray(fakecertBytes);

    req = genRenewalReq(fakeUserDN, this.cacert, this.nonce, this.transid, keys, false, null, null, pAlg,
            new DEROctetString(this.nonce));
    assertNotNull("Failed to generate a CMP renewal request", req);

    extraCert = getCMPCert(fakeCert);
    req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, keys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");
    assertNotNull(req);

    bao = new ByteArrayOutputStream();
    out = new DEROutputStream(bao);
    out.writeObject(req);
    ba = bao.toByteArray();
    // Send request and receive response
    resp = sendCmpHttp(ba, 200, this.cmpAlias);
    checkCmpResponseGeneral(resp, this.issuerDN, this.userDN, this.cacert, this.nonce, this.transid, false,
            null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());

    respObject = null;
    asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    assertNotNull(respObject);

    body = respObject.getBody();
    assertEquals(23, body.getType());
    err = (ErrorMsgContent) body.getContent();
    errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
    expectedErrMsg = "The certificate attached to the PKIMessage in the extraCert field could not be found in the database.";
    assertEquals(expectedErrMsg, errMsg);

    if (log.isTraceEnabled()) {
        log.trace("<test04UpdateKeyWithFakeCert");
    }

}

From source file:com.netscape.cmsutil.crypto.CryptoUtil.java

public static PKCS10 createCertificationRequest(String subjectName, KeyPair keyPair, String alg)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, IOException,
        CertificateException, SignatureException {
    PublicKey pubk = keyPair.getPublic();
    X509Key key = convertPublicKeyToX509Key(pubk);

    java.security.Signature sig = java.security.Signature.getInstance(alg, "Mozilla-JSS");

    sig.initSign(keyPair.getPrivate());

    PKCS10 pkcs10 = new PKCS10(key);

    X500Name name = new X500Name(subjectName);
    X500Signer signer = new X500Signer(sig, name);

    pkcs10.encodeAndSign(signer);/* w  w w. j a v a 2 s  . c  om*/

    return pkcs10;
}

From source file:net.jmhertlein.mcanalytics.console.gui.LoginPane.java

@FXML
public void onLoginButtonPressed(ActionEvent event) {
    HostEntry selected = hostList.getSelectionModel().getSelectedItem();
    if (selected == null)
        return;//w ww . ja  v  a 2s  .c  o  m

    try {
        SSLContext ctx = SSLUtil.buildClientContext(trust);
        SSLSocket raw = (SSLSocket) ctx.getSocketFactory().createSocket(selected.getUrl(), selected.getPort());
        raw.setWantClientAuth(true);
        try {
            System.out.println("Starting handshake...");
            raw.startHandshake();
        } catch (SSLException ssle) {
            if (ssle.getCause() instanceof UntrustedCertificateException) {
                System.out.println("Got the correct exception");
                UntrustedCertificateException uce = (UntrustedCertificateException) ssle.getCause();
                CertTrustPromptDialog dlg = new CertTrustPromptDialog(trust,
                        (X509Certificate) uce.getChain()[0]);
                dlg.showAndWait();
                System.out.println("DIALOG RETURNED");
            }
            return;
        }

        PrintWriter out = new PrintWriter(raw.getOutputStream());
        BufferedReader in = new BufferedReader(new InputStreamReader(raw.getInputStream()));
        APISocket sock = new APISocket(out, in);
        app.setAPISocket(sock);
        sock.startListener();

        //handle authentication
        boolean hasCert = false;
        FutureRequest<AuthenticationResult> login;
        if (trust.isCertificateEntry(selected.getUrl())) {
            try {
                ((X509Certificate) trust.getCertificate(selected.getUrl())).checkValidity();
                hasCert = true;
            } catch (CertificateExpiredException | CertificateNotYetValidException ex) {
                Logger.getLogger(LoginPane.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        System.out.println("Has cert: " + hasCert);
        KeyPair newPair = null;
        String username;

        if (hasCert) {
            username = SSLUtil.getCNs((X509Certificate) trust.getCertificate(selected.getUrl())).iterator()
                    .next();
            login = sock.submit(new AuthenticationRequest(username));
            System.out.println("Logging in w/ cert. CN: " + username + ", URL: " + selected.getUrl());
        } else if (rememberLoginBox.isSelected()) {
            newPair = SSLUtil.newECDSAKeyPair();
            username = usernameField.getText();
            PKCS10CertificationRequest csr = SSLUtil.newCertificateRequest(
                    SSLUtil.newX500Name(username, selected.getUrl(), "mcanalytics"), newPair);
            login = sock
                    .submit(new AuthenticationRequest(usernameField.getText(), passwordField.getText(), csr));
            System.out.println("Logging in with: " + usernameField.getText() + " + " + passwordField.getText()
                    + " and requesting a cert.");
        } else {
            username = usernameField.getText();
            login = sock.submit(new AuthenticationRequest(username, passwordField.getText()));
            System.out.println("Logging in with: " + username + " + " + passwordField.getText());
        }

        try {
            boolean success = login.get().getSuccess();
            if (success) {
                System.out.println("Login successful");
                if (login.get().hasCertificate()) {
                    trust.setCertificateEntry(selected.getUrl(), login.get().getCert());
                    trust.setKeyEntry(selected.getUrl() + "-private", newPair.getPrivate(), new char[0],
                            new Certificate[] { login.get().getCert(), login.get().getCA() });
                    System.out.println("Stored a trusted cert from server.");
                }
            } else {
                System.out.println("Login failed.");
                Dialog dlg = new Dialog();
                dlg.setTitle("Login Failed");
                dlg.setContentText("Could not login- invalid login credentials.");
                dlg.showAndWait();
                return;
            }
        } catch (InterruptedException | ExecutionException | KeyStoreException ex) {
            Logger.getLogger(LoginPane.class.getName()).log(Level.SEVERE, null, ex);
            Dialogs.showMessage("Connection Error", "Connection Error", ex.getMessage(), ex.toString());
            System.out.println("Login error.");
            return;
        }
        //auth done

        Stage window = (Stage) loginButton.getScene().getWindow();
        window.setScene(new Scene(new ChartPane(username, sock)));
        window.show();
    } catch (IOException | KeyStoreException ex) {
        Logger.getLogger(LoginPane.class.getName()).log(Level.SEVERE, null, ex);
        Dialog dlg = new Dialog();
        dlg.setTitle("Connection Error");
        dlg.setContentText(ex.getMessage());
        dlg.showAndWait();
        System.out.println("Login error.");
        return;
    }
}

From source file:org.artifactory.security.SecurityServiceImpl.java

@Override
public String createEncryptedPasswordIfNeeded(UserInfo user, String password) {
    if (isPasswordEncryptionEnabled()) {
        KeyPair keyPair;
        if (StringUtils.isBlank(user.getPrivateKey())) {
            MutableUserInfo mutableUser = InfoFactoryHolder.get().copyUser(user);
            keyPair = CryptoHelper.generateKeyPair();
            mutableUser.setPrivateKey(CryptoHelper.convertToString(keyPair.getPrivate()));
            mutableUser.setPublicKey(CryptoHelper.convertToString(keyPair.getPublic()));
            updateUser(mutableUser, false);
        } else {/*  w w  w. j av  a2 s.  com*/
            keyPair = CryptoHelper.createKeyPair(user.getPrivateKey(), user.getPublicKey(), false);
        }

        SecretKey secretKey = CryptoHelper.generatePbeKeyFromKeyPair(keyPair);
        return CryptoHelper.encryptSymmetric(password, secretKey, false);
    }
    return password;
}