Search in sources :

Example 6 with KeyPair

use of com.jcraft.jsch.KeyPair in project Android-Password-Store by zeapo.

the class GitOperation method executeAfterAuthentication.

/**
 * Executes the GitCommand in an async task after creating the authentication
 *
 * @param connectionMode the server-connection mode
 * @param username       the username
 * @param sshKey         the ssh-key file
 * @param showError      show the passphrase edit text in red
 */
private void executeAfterAuthentication(final String connectionMode, final String username, @Nullable final File sshKey, final boolean showError) {
    if (connectionMode.equalsIgnoreCase("ssh-key")) {
        if (sshKey == null || !sshKey.exists()) {
            new AlertDialog.Builder(callingActivity).setMessage(callingActivity.getResources().getString(R.string.ssh_preferences_dialog_text)).setTitle(callingActivity.getResources().getString(R.string.ssh_preferences_dialog_title)).setPositiveButton(callingActivity.getResources().getString(R.string.ssh_preferences_dialog_import), new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int id) {
                    try {
                        // Ask the UserPreference to provide us with the ssh-key
                        // onResult has to be handled by the callingActivity
                        Intent intent = new Intent(callingActivity.getApplicationContext(), UserPreference.class);
                        intent.putExtra("operation", "get_ssh_key");
                        callingActivity.startActivityForResult(intent, GET_SSH_KEY_FROM_CLONE);
                    } catch (Exception e) {
                        System.out.println("Exception caught :(");
                        e.printStackTrace();
                    }
                }
            }).setNegativeButton(callingActivity.getResources().getString(R.string.ssh_preferences_dialog_generate), new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    try {
                        // Duplicated code
                        Intent intent = new Intent(callingActivity.getApplicationContext(), UserPreference.class);
                        intent.putExtra("operation", "make_ssh_key");
                        callingActivity.startActivityForResult(intent, GET_SSH_KEY_FROM_CLONE);
                    } catch (Exception e) {
                        System.out.println("Exception caught :(");
                        e.printStackTrace();
                    }
                }
            }).setNeutralButton(callingActivity.getResources().getString(R.string.dialog_cancel), new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int id) {
                    // Finish the blank GitActivity so user doesn't have to press back
                    callingActivity.finish();
                }
            }).show();
        } else {
            LayoutInflater layoutInflater = LayoutInflater.from(callingActivity.getApplicationContext());
            @SuppressLint("InflateParams") final View dialogView = layoutInflater.inflate(R.layout.git_passphrase_layout, null);
            final EditText passphrase = (EditText) dialogView.findViewById(R.id.sshkey_passphrase);
            final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(callingActivity.getApplicationContext());
            final String sshKeyPassphrase = settings.getString("ssh_key_passphrase", null);
            if (showError) {
                passphrase.setError("Wrong passphrase");
            }
            JSch jsch = new JSch();
            try {
                final KeyPair keyPair = KeyPair.load(jsch, callingActivity.getFilesDir() + "/.ssh_key");
                if (keyPair.isEncrypted()) {
                    if (sshKeyPassphrase != null && !sshKeyPassphrase.isEmpty()) {
                        if (keyPair.decrypt(sshKeyPassphrase)) {
                            // Authenticate using the ssh-key and then execute the command
                            setAuthentication(sshKey, username, sshKeyPassphrase).execute();
                        } else {
                            // call back the method
                            executeAfterAuthentication(connectionMode, username, sshKey, true);
                        }
                    } else {
                        new AlertDialog.Builder(callingActivity).setTitle(callingActivity.getResources().getString(R.string.passphrase_dialog_title)).setMessage(callingActivity.getResources().getString(R.string.passphrase_dialog_text)).setView(dialogView).setPositiveButton(callingActivity.getResources().getString(R.string.dialog_ok), new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int whichButton) {
                                if (keyPair.decrypt(passphrase.getText().toString())) {
                                    boolean rememberPassphrase = ((CheckBox) dialogView.findViewById(R.id.sshkey_remember_passphrase)).isChecked();
                                    if (rememberPassphrase) {
                                        settings.edit().putString("ssh_key_passphrase", passphrase.getText().toString()).apply();
                                    }
                                    // Authenticate using the ssh-key and then execute the command
                                    setAuthentication(sshKey, username, passphrase.getText().toString()).execute();
                                } else {
                                    settings.edit().putString("ssh_key_passphrase", null).apply();
                                    // call back the method
                                    executeAfterAuthentication(connectionMode, username, sshKey, true);
                                }
                            }
                        }).setNegativeButton(callingActivity.getResources().getString(R.string.dialog_cancel), new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int whichButton) {
                            // Do nothing.
                            }
                        }).show();
                    }
                } else {
                    setAuthentication(sshKey, username, "").execute();
                }
            } catch (JSchException e) {
                new AlertDialog.Builder(callingActivity).setTitle("Unable to open the ssh-key").setMessage("Please check that it was imported.").setPositiveButton("Ok", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                }).show();
            }
        }
    } else {
        final EditText password = new EditText(callingActivity);
        password.setHint("Password");
        password.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
        password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        new AlertDialog.Builder(callingActivity).setTitle(callingActivity.getResources().getString(R.string.passphrase_dialog_title)).setMessage(callingActivity.getResources().getString(R.string.password_dialog_text)).setView(password).setPositiveButton(callingActivity.getResources().getString(R.string.dialog_ok), new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int whichButton) {
                // authenticate using the user/pwd and then execute the command
                setAuthentication(username, password.getText().toString()).execute();
            }
        }).setNegativeButton(callingActivity.getResources().getString(R.string.dialog_cancel), new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int whichButton) {
            // Do nothing.
            }
        }).show();
    }
}
Also used : EditText(android.widget.EditText) JSchException(com.jcraft.jsch.JSchException) AlertDialog(android.support.v7.app.AlertDialog) KeyPair(com.jcraft.jsch.KeyPair) DialogInterface(android.content.DialogInterface) SharedPreferences(android.content.SharedPreferences) Intent(android.content.Intent) JSch(com.jcraft.jsch.JSch) View(android.view.View) JSchException(com.jcraft.jsch.JSchException) SuppressLint(android.annotation.SuppressLint) LayoutInflater(android.view.LayoutInflater) SuppressLint(android.annotation.SuppressLint) UserPreference(com.zeapo.pwdstore.UserPreference)

Example 7 with KeyPair

use of com.jcraft.jsch.KeyPair in project airavata by apache.

the class SSHCredentialGenerator method generateCredential.

/**
 * @return a SSH Credential generated and encrypted using a randomly generated password
 * @throws CredentialStoreException
 */
public SSHCredential generateCredential(String tokenId) throws CredentialStoreException {
    JSch jsch = new JSch();
    try {
        KeyPair kpair = KeyPair.genKeyPair(jsch, KeyPair.RSA);
        File file;
        file = File.createTempFile("id_rsa", "");
        String fileName = file.getAbsolutePath();
        String password = generateRandomString();
        // We are encrypting the private key with the hash of (tokenId+password).
        // Any client which wants to use this private key will also generate a hash and then use it to decrypt the key.
        kpair.writePrivateKey(fileName, password.getBytes());
        kpair.writePublicKey(fileName + ".pub", "");
        kpair.dispose();
        byte[] priKey = FileUtils.readFileToByteArray(new File(fileName));
        byte[] pubKey = FileUtils.readFileToByteArray(new File(fileName + ".pub"));
        SSHCredential sshCredential = new SSHCredential();
        sshCredential.setPrivateKey(priKey);
        sshCredential.setPublicKey(pubKey);
        sshCredential.setPassphrase(password);
        return sshCredential;
    } catch (IOException e) {
        logger.error("IO Exception when creating SSH credential ", e);
        throw new CredentialStoreException("Unable to generate SSH Credential", e);
    } catch (JSchException e) {
        logger.error("JSch SSH credential creation exception ", e);
        throw new CredentialStoreException("Unable to generate SSH Credential. JSch exception ", e);
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) KeyPair(com.jcraft.jsch.KeyPair) IOException(java.io.IOException) CredentialStoreException(org.apache.airavata.credential.store.store.CredentialStoreException) JSch(com.jcraft.jsch.JSch) File(java.io.File)

Example 8 with KeyPair

use of com.jcraft.jsch.KeyPair in project airavata by apache.

the class Utility method generateKeyPair.

public static org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential generateKeyPair(SSHCredential credential) throws Exception {
    JSch jsch = new JSch();
    try {
        KeyPair kpair = KeyPair.genKeyPair(jsch, KeyPair.RSA, 2048);
        File file = File.createTempFile("id_rsa", "");
        String fileName = file.getAbsolutePath();
        kpair.writePrivateKey(fileName, credential.getPassphrase().getBytes());
        kpair.writePublicKey(fileName + ".pub", "");
        kpair.dispose();
        byte[] priKey = FileUtils.readFileToByteArray(new File(fileName));
        byte[] pubKey = FileUtils.readFileToByteArray(new File(fileName + ".pub"));
        credential.setPrivateKey(priKey);
        credential.setPublicKey(pubKey);
        return credential;
    } catch (Exception e) {
        log.error("Error while creating key pair", e);
        throw new Exception("Error while creating key pair", e);
    }
}
Also used : KeyPair(com.jcraft.jsch.KeyPair) JSch(com.jcraft.jsch.JSch) File(java.io.File) ParseException(java.text.ParseException)

Example 9 with KeyPair

use of com.jcraft.jsch.KeyPair in project MGit by maks.

the class SGitSessionFactory method createDefaultJSch.

@Override
protected JSch createDefaultJSch(FS fs) throws JSchException {
    JSch jsch = new JSch();
    PrivateKeyUtils.migratePrivateKeys();
    File sshDir = PrivateKeyUtils.getPrivateKeyFolder();
    for (File file : sshDir.listFiles()) {
        KeyPair kpair = KeyPair.load(jsch, file.getAbsolutePath());
        jsch.addIdentity(file.getAbsolutePath());
    }
    return jsch;
}
Also used : KeyPair(com.jcraft.jsch.KeyPair) JSch(com.jcraft.jsch.JSch) File(java.io.File)

Example 10 with KeyPair

use of com.jcraft.jsch.KeyPair in project MGit by maks.

the class PrivateKeyUtils method getPublicKeyEnsure.

public static File getPublicKeyEnsure(File privateKey) {
    File publicKey = getPublicKey(privateKey);
    if (!publicKey.exists()) {
        try {
            JSch jsch = new JSch();
            KeyPair kpair = KeyPair.load(jsch, privateKey.getAbsolutePath());
            kpair.writePublicKey(new FileOutputStream(publicKey), "mgit");
            kpair.dispose();
        } catch (Exception e) {
            // TODO
            e.printStackTrace();
        }
    }
    return publicKey;
}
Also used : KeyPair(com.jcraft.jsch.KeyPair) FileOutputStream(java.io.FileOutputStream) JSch(com.jcraft.jsch.JSch) File(java.io.File) IOException(java.io.IOException)

Aggregations

KeyPair (com.jcraft.jsch.KeyPair)30 JSch (com.jcraft.jsch.JSch)27 JSchException (com.jcraft.jsch.JSchException)13 ByteArrayOutputStream (java.io.ByteArrayOutputStream)12 File (java.io.File)10 IOException (java.io.IOException)9 OutputStream (java.io.OutputStream)3 BasicSSHUserPrivateKey (com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey)2 SSHKeyPair (io.cdap.cdap.runtime.spi.ssh.SSHKeyPair)2 SSHPublicKey (io.cdap.cdap.runtime.spi.ssh.SSHPublicKey)2 FileOutputStream (java.io.FileOutputStream)2 KeyException (java.security.KeyException)2 ArrayList (java.util.ArrayList)2 SuppressLint (android.annotation.SuppressLint)1 DialogInterface (android.content.DialogInterface)1 Intent (android.content.Intent)1 SharedPreferences (android.content.SharedPreferences)1 AlertDialog (android.support.v7.app.AlertDialog)1 LayoutInflater (android.view.LayoutInflater)1 View (android.view.View)1