com.jcraft.jsch.KeyPair Java Examples

The following examples show how to use com.jcraft.jsch.KeyPair. 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: TransUtil.java    From oneops with Apache License 2.0 6 votes vote down vote up
public Map<String,String> keyGen(String passPhrase, String pubDesc) {
	JSch jsch=new JSch();
       String passphrase= (passPhrase == null) ? "" : passPhrase;
       Map<String,String> result = new HashMap<String,String>();
       try{
        KeyPair kpair=KeyPair.genKeyPair(jsch, KeyPair.RSA, 2048);
        kpair.setPassphrase(passphrase);
        OutputStream prkos = new ByteArrayOutputStream();
        kpair.writePrivateKey(prkos);
        String privateKey = prkos.toString();
        //removing "\n" at the end of the string
        result.put("private", privateKey.substring(0, privateKey.length() - 1));
        OutputStream pubkos = new ByteArrayOutputStream();
        kpair.writePublicKey(pubkos, pubDesc);
        String pubKey = pubkos.toString();
        //removing "\n" at the end of the string
        result.put("public", pubKey.substring(0, pubKey.length() - 1));
        kpair.dispose();
        return result;
       } catch(Exception e){
       	System.out.println(e);
       	logger.error(e.getMessage());
       	throw new TransistorException(CmsError.TRANSISTOR_EXCEPTION, e.getMessage());
       }
}
 
Example #2
Source File: KeyPairActivity.java    From trigger with GNU General Public License v2.0 6 votes vote down vote up
private void importKeys() {
    if (selected_path == null) {
        showErrorMessage("No Directory Selected", "No directory for import selected.");
    } else if (!Utils.hasReadPermission(this)) {
        Utils.requestReadPermission(this, REQUEST_PERMISSION);
    } else try {
        byte[] prvkey = Utils.readExternalFile(selected_path + "/id_rsa");
        byte[] pubkey = Utils.readExternalFile(selected_path + "/id_rsa.pub");

        JSch jsch = new JSch();
        KeyPairActivity.this.keypair = KeyPair.load(jsch, prvkey, pubkey);

        Toast.makeText(getApplicationContext(), "Done. Read 'id_rsa.pub' and 'id_rsa'.", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        showErrorMessage("Error", e.getMessage());
    }
}
 
Example #3
Source File: TestSshTunnel.java    From datacollector with Apache License 2.0 6 votes vote down vote up
String getSshdHostFingerprint(java.security.KeyPair keyPair) throws Exception {
  RSAPublicKey rsapubkey = (RSAPublicKey) keyPair.getPublic();
  byte[] modulus = rsapubkey.getModulus().toByteArray();
  byte[] exponent = rsapubkey.getPublicExponent().toByteArray();
  byte[] tag = "ssh-rsa".getBytes();
  ByteArrayOutputStream os = new ByteArrayOutputStream();
  DataOutputStream dos = new DataOutputStream(os);
  dos.writeInt(tag.length);
  dos.write(tag);
  dos.writeInt(exponent.length);
  dos.write(exponent);
  dos.writeInt(modulus.length);
  dos.write(modulus);
  byte[] encoded = os.toByteArray();
  MessageDigest digest = MessageDigest.getInstance("SHA-256");
  byte[] result = digest.digest(encoded);
  return "SHA256:" + Base64.getEncoder().encodeToString(result);
}
 
Example #4
Source File: KeyPairService.java    From cloud-portal with MIT License 6 votes vote down vote up
public List<File> createKeyPair() {

		List<File> keyFileList = new ArrayList<>(); 
		
		try{
			File privateKeyFile = File.createTempFile(Constants.KEY_FILE_PREFIX, Constants.CHAR_EMPTY);
			File publicKeyFile = new File(privateKeyFile.getAbsolutePath() + Constants.KEY_FILE_PUBLIC_SUFFIX);
			
			KeyPair keyPair = KeyPair.genKeyPair(JSCH, KeyPair.RSA);
			keyPair.writePrivateKey(privateKeyFile.getAbsolutePath());
			keyPair.writePublicKey(publicKeyFile.getAbsolutePath(), COMMENT);
			keyPair.dispose();
			
			keyFileList.add(privateKeyFile);
			keyFileList.add(publicKeyFile);
		}
		catch(Exception e){
			LOG.error(e.getMessage(), e);
		}
		
		return keyFileList;
	}
 
Example #5
Source File: SshManager.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Generates and stores ssh pair for specified user.
 *
 * @param owner the id of the user who will be the owner of the ssh pair
 * @param service service name pf ssh pair
 * @param name name of pair
 * @return instance of generated ssh pair
 * @throws ConflictException when given ssh pair cannot be generated or created
 * @throws ServerException when any other error occurs during ssh pair generating or creating
 */
public SshPairImpl generatePair(String owner, String service, String name)
    throws ServerException, ConflictException {
  KeyPair keyPair;
  try {
    keyPair = KeyPair.genKeyPair(genJSch, 2, 2048);
  } catch (JSchException e) {
    throw new ServerException("Failed to generate ssh pair.", e);
  }

  ByteArrayOutputStream privateBuff = new ByteArrayOutputStream();
  keyPair.writePrivateKey(privateBuff);

  ByteArrayOutputStream publicBuff = new ByteArrayOutputStream();
  keyPair.writePublicKey(publicBuff, null);

  final SshPairImpl generatedSshPair =
      new SshPairImpl(owner, service, name, publicBuff.toString(), privateBuff.toString());
  sshDao.create(generatedSshPair);
  return generatedSshPair;
}
 
Example #6
Source File: SSHShell.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
/**
 * Automatically generate SSH keys.
 * @param passPhrase the byte array content to be uploaded
 * @param comment the name of the file for which the content will be saved into
 * @return SSH public and private key
 * @throws Exception exception thrown
 */
public static SshPublicPrivateKey generateSSHKeys(String passPhrase, String comment) throws Exception {
    JSch jsch = new JSch();
    KeyPair keyPair = KeyPair.genKeyPair(jsch, KeyPair.RSA);
    ByteArrayOutputStream privateKeyBuff = new ByteArrayOutputStream(2048);
    ByteArrayOutputStream publicKeyBuff = new ByteArrayOutputStream(2048);

    keyPair.writePublicKey(publicKeyBuff, (comment != null) ? comment : "SSHCerts");

    if (passPhrase == null  || passPhrase.isEmpty()) {
        keyPair.writePrivateKey(privateKeyBuff);
    } else {
        keyPair.writePrivateKey(privateKeyBuff, passPhrase.getBytes());
    }

    return new SshPublicPrivateKey(privateKeyBuff.toString(), publicKeyBuff.toString());
}
 
Example #7
Source File: CipherHelper.java    From flow-platform-x with Apache License 2.0 6 votes vote down vote up
public static SimpleKeyPair gen(String email) {
    try (ByteArrayOutputStream pubKeyOS = new ByteArrayOutputStream()) {
        try (ByteArrayOutputStream prvKeyOS = new ByteArrayOutputStream()) {
            JSch jsch = new JSch();
            SimpleKeyPair rsa = new SimpleKeyPair();

            KeyPair kpair = KeyPair.genKeyPair(jsch, KeyPair.RSA, 2048);
            kpair.writePrivateKey(prvKeyOS);
            kpair.writePublicKey(pubKeyOS, email);

            rsa.setPublicKey(pubKeyOS.toString());
            rsa.setPrivateKey(prvKeyOS.toString());

            kpair.dispose();
            return rsa;
        }
    } catch (IOException | JSchException e) {
        throw new StatusException("Unable to generate RSA key pair");
    }
}
 
Example #8
Source File: SshTools.java    From trigger with GNU General Public License v2.0 6 votes vote down vote up
public static KeyPair deserializeKeyPairOld(String str) {
    if (str == null || str.length() == 0) {
        return null;
    }

    try {
        // base64 string to bytes
        byte[] bytes = Base64.decode(str, Base64.DEFAULT);

        // bytes to KeyPairData
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        ObjectInputStream ios = new ObjectInputStream(bais);
        KeyPairData obj = (KeyPairData) ios.readObject();

        // KeyParData to KeyPair
        JSch jsch = new JSch();
        KeyPair keypair = KeyPair.load(jsch, obj.prvkey, obj.pubkey);
        if (keypair != null) {
            keypair.setPublicKeyComment(null);
        }
        return keypair;
    } catch (Exception e) {
        Log.e(TAG, "deserialize error: " + e.toString());
    }
    return null;
}
 
Example #9
Source File: SshTools.java    From trigger with GNU General Public License v2.0 6 votes vote down vote up
public static KeyPair deserializeKeyPair(String str) {
    if (str == null || str.length() == 0) {
        return null;
    }

    try {
        JSch jsch = new JSch();
        KeyPair keypair = KeyPair.load(jsch, str.getBytes(), null);
        keypair.setPublicKeyComment(null);

        return keypair;
    } catch (Exception e) {
        Log.e(TAG, "deserialize error: " + e.toString());
    }
    return null;
}
 
Example #10
Source File: SshTools.java    From trigger with GNU General Public License v2.0 6 votes vote down vote up
public static KeyPairData keypairToBytes(KeyPair keypair) {
    try {
        ByteArrayOutputStream prvstream = new ByteArrayOutputStream();
        ByteArrayOutputStream pubstream = new ByteArrayOutputStream();

        keypair.writePrivateKey(prvstream);
        keypair.writePublicKey(pubstream, keypair.getPublicKeyComment());
        prvstream.close();
        pubstream.close();

        return new KeyPairData(prvstream.toByteArray(), pubstream.toByteArray());
    } catch (Exception e) {
        Log.e(TAG ,"keypairtoBytes " + e.toString());
    }
    return null;
}
 
Example #11
Source File: CipherHelper.java    From flow-platform-x with Apache License 2.0 6 votes vote down vote up
public static SimpleKeyPair gen(String email) {
    try (ByteArrayOutputStream pubKeyOS = new ByteArrayOutputStream()) {
        try (ByteArrayOutputStream prvKeyOS = new ByteArrayOutputStream()) {
            JSch jsch = new JSch();
            SimpleKeyPair rsa = new SimpleKeyPair();

            KeyPair kpair = KeyPair.genKeyPair(jsch, KeyPair.RSA, 2048);
            kpair.writePrivateKey(prvKeyOS);
            kpair.writePublicKey(pubKeyOS, email);

            rsa.setPublicKey(pubKeyOS.toString());
            rsa.setPrivateKey(prvKeyOS.toString());

            kpair.dispose();
            return rsa;
        }
    } catch (IOException | JSchException e) {
        throw new StatusException("Unable to generate RSA key pair");
    }
}
 
Example #12
Source File: GitReadSaveTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
private void startSSH(@Nullable User u) throws Exception {
    if (sshd == null) {
        // Set up an SSH server with access to a git repo
        User user;
        if(u == null) {
            user = login();
        } else {
            user = u;
        }
        final BasicSSHUserPrivateKey key = UserSSHKeyManager.getOrCreate(user);
        final JSch jsch = new JSch();
        final KeyPair pair = KeyPair.load(jsch, key.getPrivateKey().getBytes(), null);

        File keyFile = new File(System.getProperty("TEST_SSH_SERVER_KEY_FILE", File.createTempFile("hostkey", "ser").getCanonicalPath()));
        int port = Integer.parseInt(System.getProperty("TEST_SSH_SERVER_PORT", "0"));
        boolean allowLocalUser = Boolean.getBoolean("TEST_SSH_SERVER_ALLOW_LOCAL");
        String userPublicKey = Base64.encode(pair.getPublicKeyBlob());
        sshd = new SSHServer(repoForSSH.getRoot(), keyFile, port, allowLocalUser, ImmutableMap.of("bob", userPublicKey), true);
        // Go, go, go
        sshd.start();
    }
}
 
Example #13
Source File: KeySettingActivity.java    From mOrgAnd with GNU General Public License v2.0 6 votes vote down vote up
private String GetKeyprint(String keyfilePath, String passphrase) {
    try {
        KeyPair keyPair = KeyPair.load(new JSch(), keyfilePath);
        if (!passphrase.isEmpty() && keyPair.isEncrypted())
            keyPair.decrypt(passphrase);
        else if (passphrase.isEmpty() && keyPair.isEncrypted()) {
            Toast.makeText(this, R.string.error_key_need_pass, Toast.LENGTH_LONG).show();
            return "";
        }
        String fingerprint = keyPair.getFingerPrint();
        keyPair.dispose();
        return fingerprint;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}
 
Example #14
Source File: SshkeyExchange.java    From onos with Apache License 2.0 6 votes vote down vote up
private boolean generateKeyPair() {
    KeyPair kpair;
    StringBuilder command = new StringBuilder()
            .append("chmod 600 ")
            .append(HOME_ENV)
            .append(PRIVATE_KEY);
    try {
        kpair = KeyPair.genKeyPair(new JSch(), KeyPair.RSA, KEY_SIZE);
        kpair.writePrivateKey(HOME_ENV + PRIVATE_KEY);
        kpair.writePublicKey(HOME_ENV + PUBLIC_KEY, USER_ENV);
        Runtime.getRuntime().exec(command.toString());
        kpair.dispose();
    } catch (JSchException | IOException e) {
        log.error("Exception in generateKeyPair", e);
        return false;
    }
    return true;
}
 
Example #15
Source File: SystemInfo.java    From app-runner with MIT License 6 votes vote down vote up
private static List<String> getPublicKeys() throws Exception {
    return new JschConfigSessionFactory() {
        @Override
        protected void configure(OpenSshConfig.Host hc, Session session) {
        }
        List<String> getPublicKeys() throws Exception {
            JSch jSch = createDefaultJSch(FS.DETECTED);
            List<String> keys = new ArrayList<>();
            for (Object o : jSch.getIdentityRepository().getIdentities()) {
                Identity i = (Identity) o;
                KeyPair keyPair = KeyPair.load(jSch, i.getName(), null);
                StringBuilder sb = new StringBuilder();
                try (StringBuilderWriter sbw = new StringBuilderWriter(sb);
                     OutputStream os = new WriterOutputStream(sbw, "UTF-8")) {
                    keyPair.writePublicKey(os, keyPair.getPublicKeyComment());
                } finally {
                    keyPair.dispose();
                }
                keys.add(sb.toString().trim());
            }
            return keys;
        }
    }.getPublicKeys();
}
 
Example #16
Source File: TestSshTunnel.java    From datacollector with Apache License 2.0 5 votes vote down vote up
private SshServer createSshd(PublickeyAuthenticator publickeyAuthenticator, java.security.KeyPair sshdKeyPair) {
  SshServer sshd = SshServer.setUpDefaultServer();
  sshd.setHost("localhost");
  sshd.setPort(randomPort());

  KeyPairProvider keyPairProvider = KeyPairProvider.wrap(sshdKeyPair);
  sshd.setKeyPairProvider(keyPairProvider);

  sshd.setForwardingFilter(AcceptAllForwardingFilter.INSTANCE);
  sshd.setPublickeyAuthenticator(publickeyAuthenticator);
  return sshd;
}
 
Example #17
Source File: AAWSTest.java    From aws-ec2-ssh with MIT License 5 votes vote down vote up
protected final User createUser(final String userName) throws JSchException {
    final JSch jsch = new JSch();
    final KeyPair keyPair = KeyPair.genKeyPair(jsch, KeyPair.RSA, 2048);
    final ByteArrayOutputStream osPublicKey = new ByteArrayOutputStream();
    final ByteArrayOutputStream osPrivateKey = new ByteArrayOutputStream();
    keyPair.writePublicKey(osPublicKey, userName);
    keyPair.writePrivateKey(osPrivateKey);
    final byte[] sshPrivateKeyBlob = osPrivateKey.toByteArray();
    final String sshPublicKeyBody = osPublicKey.toString();
    this.iam.createUser(new CreateUserRequest().withUserName(userName));
    final UploadSSHPublicKeyResult res = this.iam.uploadSSHPublicKey(new UploadSSHPublicKeyRequest().withUserName(userName).withSSHPublicKeyBody(sshPublicKeyBody));
    return new User(userName, sshPrivateKeyBlob, res.getSSHPublicKey().getSSHPublicKeyId());
}
 
Example #18
Source File: TestSshTunnel.java    From datacollector with Apache License 2.0 5 votes vote down vote up
KeyPair createSshKeyPair(int len) {
  try {
    return KeyPair.genKeyPair(new JSch(), KeyPair.RSA, len);
  } catch (Exception ex) {
    throw new RuntimeException(ex);
  }
}
 
Example #19
Source File: TestSshTunnel.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Before
public void before() throws Exception {
  sshdKeyPair = createSshdHostKeyPair(4096);
  sshdFingerprint = getSshdHostFingerprint(sshdKeyPair);

  privKeyPass = UUID.randomUUID().toString();
  KeyPair keyPair = createSshKeyPair(4096);
  privKey = getSshPrivateKeyText(keyPair, privKeyPass);
  pubKey = getSshPublicKeyText(keyPair, "foo@cloud");
}
 
Example #20
Source File: SSHKeyUtils.java    From blueocean-plugin with MIT License 5 votes vote down vote up
/**
 * Gets the public key, with a comment for the given private key
 * @param privateKey SSH private key to use
 * @param comment comment with the key
 * @return SSH public key
 */
public static String getPublicKey(String privateKey, String comment) {
    try {
        JSch jsch = new JSch();
        KeyPair pair = KeyPair.load(jsch, privateKey.getBytes("utf-8"), null );
        ByteArrayOutputStream keyOut = new ByteArrayOutputStream();
        pair.writePublicKey(keyOut, comment);
        return new String(keyOut.toByteArray(), "utf-8");
    } catch(Exception ex) {
        throw ex instanceof RuntimeException ? (RuntimeException)ex : new RuntimeException(ex);
    }
}
 
Example #21
Source File: SshUtils.java    From datacollector with Apache License 2.0 5 votes vote down vote up
public static SshKeyInfoBean createSshKeyInfoBean(int len, String comment) {
  SshKeyInfoBean bean = new SshKeyInfoBean();
  KeyPair keys = createSshKeyPair(len);
  bean.password = UUID.randomUUID().toString();
  bean.privateKey = getSshPrivateKeyText(keys, bean.password);
  bean.publicKey = getSshPublicKeyText(keys, comment);
  return bean;
}
 
Example #22
Source File: SshUtils.java    From datacollector with Apache License 2.0 5 votes vote down vote up
private static KeyPair createSshKeyPair(int len) {
  try {
    return KeyPair.genKeyPair(new JSch(), KeyPair.RSA, len);
  } catch (Exception ex) {
    throw new RuntimeException(ex);
  }
}
 
Example #23
Source File: PrivateKeyValidator.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
private boolean isPrivateKeyFormatCorrect(JGitEnvironmentProperties sshUriProperties,
		ConstraintValidatorContext context) {
	try {
		KeyPair.load(new JSch(), sshUriProperties.getPrivateKey().getBytes(), null);
		return true;
	}
	catch (JSchException e) {
		context.buildConstraintViolationWithTemplate(
				format("Property '%sprivateKey' is not a valid private key",
						GIT_PROPERTY_PREFIX))
				.addConstraintViolation();
		return false;
	}
}
 
Example #24
Source File: SshUtil.java    From gerrit-events with MIT License 5 votes vote down vote up
/**
 * Parses the keyFile hiding any Exceptions that might occur.
 * @param keyFile the file.
 * @return the "parsed" file.
 */
private static KeyPair parsePrivateKeyFile(File keyFile) {
    if (keyFile == null) {
      return null;
    }

    try {
        JSch jsch = new JSch();
        KeyPair key = KeyPair.load(jsch, keyFile.getAbsolutePath());
        return key;
    } catch (JSchException ex) {
        return null;
    }
}
 
Example #25
Source File: SshUtil.java    From gerrit-events with MIT License 5 votes vote down vote up
/**
 * Checks to see if the passPhrase is valid for the private key file.
 * @param keyFilePath the private key file.
 * @param passPhrase the password for the file.
 * @return true if it is valid.
 */
public static boolean checkPassPhrase(File keyFilePath, String passPhrase) {
    KeyPair key = parsePrivateKeyFile(keyFilePath);
    boolean isValidPhrase = passPhrase != null && !passPhrase.trim().isEmpty();
    if (key == null) {
        return false;
    } else if (key.isEncrypted() != isValidPhrase) {
        return false;
    } else if (key.isEncrypted()) {
        return key.decrypt(passPhrase);
    }
    return true;
}
 
Example #26
Source File: SshdServerMock.java    From gerrit-events with MIT License 5 votes vote down vote up
/**
 * Generates a rsa key-pair in /tmp/jenkins-testkey for use with authenticating the trigger against the mock
 * server.
 *
 * @return the path to the private key file
 *
 * @throws IOException          if so.
 * @throws InterruptedException if interrupted while waiting for ssh-keygen to finish.
 * @throws JSchException        if creation of the keys goes wrong.
 */
public static KeyPairFiles generateKeyPair() throws IOException, InterruptedException, JSchException {
    File tmp = new File(System.getProperty("java.io.tmpdir")).getCanonicalFile();
    File priv = new File(tmp, "jenkins-testkey");
    File pub = new File(tmp, "jenkins-testkey.pub");
    if (!(priv.exists() && pub.exists())) {
        if (priv.exists()) {
            if (!priv.delete()) {
                throw new IOException("Could not delete temp private key");
            }
        }
        if (pub.exists()) {
            if (!pub.delete()) {
                throw new IOException("Could not delete temp public key");
            }
        }
        System.out.println("Generating test key-pair.");
        JSch jsch = new JSch();
        KeyPair kpair = KeyPair.genKeyPair(jsch, KeyPair.RSA);

        kpair.writePrivateKey(new FileOutputStream(priv));
        kpair.writePublicKey(new FileOutputStream(pub), "Test");
        System.out.println("Finger print: " + kpair.getFingerPrint());
        kpair.dispose();
        return new KeyPairFiles(priv, pub);
    } else {
        System.out.println("Test key-pair seems to already exist.");
        return new KeyPairFiles(priv, pub);
    }
}
 
Example #27
Source File: SSHKeysHelper.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public SSHKeysHelper(Integer keyLength) {
    try {
        keyPair = KeyPair.genKeyPair(new JSch(), KeyPair.RSA, keyLength);
    } catch (JSchException e) {
        e.printStackTrace();
    }
}
 
Example #28
Source File: KeyPairPreference.java    From trigger with GNU General Public License v2.0 5 votes vote down vote up
public void setKeyPair(KeyPair keypair) {
    this.keypair = keypair;

    if (this.keypair == null) {
        setChecked(false);
    } else {
        setChecked(true);
    }
}
 
Example #29
Source File: JschHolder.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@Override
public Ssh2KeyPair generateKeypair(AlgorithmType type, String comment) throws Exception {
	int algType = KeyPair.RSA;
	if (type == AlgorithmType.DSA) {
		algType = KeyPair.DSA;
	} else if (type == AlgorithmType.ECDSA) {
		algType = KeyPair.ECDSA;
	}
	KeyPair kpair = KeyPair.genKeyPair(new JSch(), algType);

	// 私钥
	ByteArrayOutputStream baos = new ByteArrayOutputStream();// 向OutPutStream中写入
	kpair.writePrivateKey(baos);
	final String privateKey = baos.toString();
	// 公钥
	baos = new ByteArrayOutputStream();
	kpair.writePublicKey(baos, comment);
	final String publicKey = baos.toString();
	kpair.dispose();

	// To rsa.pub
	// String publicKeyString =
	// RSAEncrypt.loadPublicKeyByFile(filePath,filename + ".pub");
	// System.out.println(publicKeyString.length());
	// System.out.println(publicKeyString);

	// To rsa
	// String privateKeyString =
	// RSAEncrypt.loadPrivateKeyByFile(filePath,filename);
	// System.out.println(privateKeyString.length());
	// System.out.println(privateKeyString);

	return new Ssh2KeyPair(privateKey, publicKey);
}
 
Example #30
Source File: SetupActivity.java    From trigger with GNU General Public License v2.0 5 votes vote down vote up
private KeyPair getKeyPair(String key) {
    KeyPairPreference kpp = (KeyPairPreference) findAnyPreference(key, null);
    if (kpp != null) {
        return kpp.getKeyPair();
    } else {
        Log.e("SetupActivity", "Cannot find KeyPairPreference in PreferenceGroup with key: " + key);
        return null;
    }
}