/** * 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()); }
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_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; }
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()); } }
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(); }
/** * 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; }
private void addPrivateKey(String filename) throws JSchException { if (filename == null || filename.isEmpty()) { return; } File file = new File(filename); if (file.exists()) { System.out.println("Adding private key: " + filename); KeyPair keyPair = KeyPair.load(this, filename); if (keyPair.isEncrypted()) { this.tryDecryptPrivateKey(filename, keyPair); this.addIdentity(file.getAbsolutePath(), this.privateKeyPassphrase); } else { this.addIdentity(file.getAbsolutePath()); } } }
public static final void generateNewIdentity(File keyDir, String comment, int strength) throws Exception { JSch jsch = new JSch(); KeyPair newKeyPair = KeyPair.genKeyPair(jsch, KeyPair.RSA, strength); File privateKeyFile = new File(keyDir, "id_rsa"); File publicKeyFile = new File(keyDir, "id_rsa.pub"); if (privateKeyFile.exists()) { privateKeyFile.delete(); } if (publicKeyFile.exists()) { publicKeyFile.delete(); } newKeyPair.writePrivateKey(new FileOutputStream(privateKeyFile)); newKeyPair.writePublicKey(new FileOutputStream(publicKeyFile), comment); newKeyPair.dispose(); }
public void genKeyPair() { createFilePath(); KeyPair kp = null; try { kp = KeyPair.genKeyPair(new JSch(), keypairType, keypairSize); kp.writePrivateKey(keypairFileName); kp.writePublicKey(keypairFileName + ".pub", keypairComment); } catch (Exception e) { e.printStackTrace(); } finally { if (kp != null) { kp.dispose(); } } }
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 ""; }
private void generateKeys() throws JSchException, IOException { String instance_name = InstanceStatus.getStatic().summary.getInstanceName(); String host_name = InstanceStatus.getStatic().summary.getHostName(); String comment = "mydmam-" + instance_name + "@" + host_name; JSch jsch = new JSch(); KeyPair kpair = KeyPair.genKeyPair(jsch, KeyPair.RSA); kpair.writePrivateKey(private_key); kpair.writePublicKey(public_key, comment); kpair.dispose(); String os_name = System.getProperty("os.name").toLowerCase(); if (os_name.indexOf("win") == -1) { ArrayList<String> params = new ArrayList<String>(); params.add("600"); params.add(private_key); ExecprocessGettext exec = new ExecprocessGettext(ExecBinaryPath.get("chmod"), params); exec.start(); } Loggers.Ssh.info("Generate SSH Keys for MyDMAM, public key: " + new File(public_key) + ", private key: " + new File(private_key) + ", finger print: " + kpair.getFingerPrint()); }
@Before public void init() throws Exception { knownHosts = tmpFolder.newFile(KNOWN_HOSTS); JSch jSch = new JSch(); KeyPair keyPair = null; identityKey1 = tmpFolder.newFile(IDENTITY_KEY_1); keyPair = KeyPair.genKeyPair(jSch, KeyPair.RSA); keyPair.writePrivateKey(identityKey1.getAbsolutePath()); identityKey2 = tmpFolder.newFile(IDENTITY_KEY_2); keyPair = KeyPair.genKeyPair(jSch, KeyPair.RSA); keyPair.writePrivateKey(identityKey2.getAbsolutePath()); }
@Override public RSAKeyPair generateRsaKey() { String comment = "FLOWCI"; int type = KeyPair.RSA; final int keySize = 2048; // default 1024, bitbucket support at least 2048 JSch jsch = new JSch(); try { KeyPair kpair = KeyPair.genKeyPair(jsch, type, keySize); RSAKeyPair pair = new RSAKeyPair(); // private key try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { kpair.writePrivateKey(baos); pair.setPrivateKey(baos.toString()); } // public key try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { kpair.writePublicKey(baos, comment); pair.setPublicKey(baos.toString()); } kpair.dispose(); return pair; } catch (JSchException | IOException e) { return null; } }
public SSHKeysHelper() { try { keyPair = KeyPair.genKeyPair(new JSch(), KeyPair.RSA); } catch (final JSchException e) { e.printStackTrace(); } }
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()); }
/** * Generates a random public key for test. * @return The encoded SSH public key. * @throws Exception If a problem occurs. */ private String key() throws Exception { final ByteArrayOutputStream stream = new ByteArrayOutputStream(); try { final KeyPair kpair = KeyPair.genKeyPair(new JSch(), KeyPair.DSA); kpair.writePublicKey(stream, ""); kpair.dispose(); } finally { stream.close(); } return new String(stream.toByteArray()); }
/** * Generates a random public key for test. * * @return The encoded SSH public key. * @throws Exception If a problem occurs. */ private static String key() throws Exception { final ByteArrayOutputStream stream = new ByteArrayOutputStream(); try { final KeyPair kpair = KeyPair.genKeyPair(new JSch(), KeyPair.DSA); kpair.writePublicKey(stream, ""); kpair.dispose(); } finally { stream.close(); } return new String(stream.toByteArray()); }
TestAccount( Account.Id id, String username, String email, String fullName, KeyPair sshKey, String httpPassword) { this.id = id; this.username = username; this.email = email; this.emailAddress = new Address(fullName, email); this.fullName = fullName; this.sshKey = sshKey; this.httpPassword = httpPassword; }
private void tryDecryptPrivateKey(String filename, KeyPair keyPair) { if (this.privateKeyPassphrase == null || this.privateKeyPassphrase.isEmpty() || !keyPair.decrypt(this.privateKeyPassphrase)) { char[] passphrase = System.console().readPassword("Enter passphrase for key '" + filename + "': "); if (passphrase == null) { System.exit(1); } this.privateKeyPassphrase = new String(passphrase); this.tryDecryptPrivateKey(filename, keyPair); } }
protected Exception doInBackground(String... strings) { int length = Integer.parseInt(strings[0]); String passphrase = strings[1]; String comment = strings[2]; JSch jsch = new JSch(); try { KeyPair kp = KeyPair.genKeyPair(jsch, KeyPair.RSA, length); File file = new File(getFilesDir() + "/.ssh_key"); FileOutputStream out = new FileOutputStream(file, false); if (passphrase.length() > 0) { kp.writePrivateKey(out, passphrase.getBytes()); } else { kp.writePrivateKey(out); } file = new File(getFilesDir() + "/.ssh_key.pub"); out = new FileOutputStream(file, false); kp.writePublicKey(out, comment); return null; } catch (Exception e) { System.out.println("Exception caught :("); e.printStackTrace(); return e; } }
private boolean isPrivateKeyFormatCorrect(SshUri 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; } }
/** * 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); } }
public SSHKeysHelper(Integer keyLength) { try { keyPair = KeyPair.genKeyPair(new JSch(), KeyPair.RSA, keyLength); } catch (JSchException e) { e.printStackTrace(); } }
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), "sgit"); kpair.dispose(); } catch (Exception e) { //TODO e.printStackTrace(); } } return publicKey; }
@Parameters(name = "{0}") public static Collection<Object[]> parameters() throws Exception { final ImmutableSet.Builder<Object[]> builder = ImmutableSet.builder(); if (GIT_PASSWORD != null) { builder.add(new Object[] { "https", "git+https://" + GIT_HOST + ':' + GIT_PORT_HTTPS + GIT_PATH, Jackson.readTree( '{' + " \"type\": \"password\"," + " \"hostnamePatterns\": [ \"^.*$\" ]," + " \"username\": \"" + GIT_USERNAME_HTTPS + "\"," + " \"password\": \"" + Jackson.escapeText(GIT_PASSWORD) + '"' + '}') }); } // Test Git-over-SSH only when the public key and private key files are readable. if (new File(GIT_PUBLIC_KEY).canRead() && new File(GIT_PRIVATE_KEY).canRead()) { final byte[] privateKeyBytes = Files.readAllBytes(Paths.get(GIT_PRIVATE_KEY)); final byte[] publicKeyBytes = Files.readAllBytes(Paths.get(GIT_PUBLIC_KEY)); final String privateKey = new String(privateKeyBytes, StandardCharsets.UTF_8); final String publicKey = new String(publicKeyBytes, StandardCharsets.UTF_8); // Test Git-over-SSH only when: // - the private key passphrase is specified or // - the private key is unencrypted. if (GIT_PASSPHRASE != null || !KeyPair.load(new JSch(), privateKeyBytes, publicKeyBytes).isEncrypted()) { final String passphraseProperty; if (GIT_PASSPHRASE != null) { passphraseProperty = "\"passphrase\": \"" + Jackson.escapeText(GIT_PASSPHRASE) + '"'; } else { passphraseProperty = "\"passphrase\": null"; } builder.add(new Object[] { "ssh", "git+ssh://" + GIT_HOST + ':' + GIT_PORT_SSH + GIT_PATH, Jackson.readTree( '{' + " \"type\": \"public_key\"," + " \"hostnamePatterns\": [ \"^.*$\" ]," + " \"username\": \"" + GIT_USERNAME_SSH + "\"," + " \"publicKey\": \"" + Jackson.escapeText(publicKey) + "\"," + " \"privateKey\": \"" + Jackson.escapeText(privateKey) + "\"," + passphraseProperty + '}') }); } } return builder.build(); }
public synchronized TestAccount create( @Nullable String username, @Nullable String email, @Nullable String fullName, String... groupNames) throws Exception { TestAccount account = accounts.get(username); if (account != null) { return account; } try (ReviewDb db = reviewDbProvider.open()) { Account.Id id = new Account.Id(sequences.nextAccountId()); List<ExternalId> extIds = new ArrayList<>(2); String httpPass = null; if (username != null) { httpPass = "http-pass"; extIds.add(ExternalId.createUsername(username, id, httpPass)); } if (email != null) { extIds.add(ExternalId.createEmail(id, email)); } externalIdsUpdate.create().insert(extIds); accountsUpdate .create() .insert( id, a -> { a.setFullName(fullName); a.setPreferredEmail(email); }); if (groupNames != null) { for (String n : groupNames) { AccountGroup.NameKey k = new AccountGroup.NameKey(n); Optional<InternalGroup> group = groupCache.get(k); if (!group.isPresent()) { throw new NoSuchGroupException(n); } addGroupMember(db, group.get().getGroupUUID(), id); } } KeyPair sshKey = null; if (sshEnabled && username != null) { sshKey = genSshKey(); authorizedKeys.addKey(id, publicKey(sshKey, email)); sshKeyCache.evict(username); } account = new TestAccount(id, username, email, fullName, sshKey, httpPass); if (username != null) { accounts.put(username, account); } return account; } }
public static KeyPair genSshKey() throws JSchException { JSch jsch = new JSch(); return KeyPair.genKeyPair(jsch, KeyPair.RSA); }
public static String publicKey(KeyPair sshKey, String comment) throws UnsupportedEncodingException { ByteArrayOutputStream out = new ByteArrayOutputStream(); sshKey.writePublicKey(out, comment); return out.toString(US_ASCII.name()).trim(); }
private void generatePrivateKey(File file) throws IOException, JSchException { KeyPair kpair = KeyPair.genKeyPair(jsch, KeyPair.RSA, PRIVATE_KEY_LENGTH); kpair.writePrivateKey(file.getAbsolutePath()); kpair.dispose(); }
private void generatePublicKey(File file) throws IOException, JSchException { KeyPair kpair = KeyPair.load(jsch, getPrivateKey().getAbsolutePath()); kpair.writePublicKey(file.getAbsolutePath(), PUBLIC_KEY_COMMENT); kpair.dispose(); }
private void generateKey() { String newFilename = mNewFilename.getText().toString().trim(); if (newFilename.equals("")) { showToastMessage(R.string.alert_new_filename_required); mNewFilename .setError(getString(R.string.alert_new_filename_required)); return; } if (newFilename.contains("/")) { showToastMessage(R.string.alert_filename_format); mNewFilename.setError(getString(R.string.alert_filename_format)); return; } int key_size = Integer.parseInt(mKeyLength.getText().toString()); if (key_size < 1024) { showToastMessage(R.string.alert_too_short_key_size); mNewFilename.setError(getString(R.string.alert_too_short_key_size)); return; } if (key_size > 16384) { showToastMessage(R.string.alert_too_long_key_size); mNewFilename.setError(getString(R.string.alert_too_long_key_size)); return; } int type = mDSAButton.isChecked() ? KeyPair.DSA : KeyPair.RSA; File newKey = new File(PrivateKeyUtils.getPrivateKeyFolder(), newFilename); File newPubKey = new File(PrivateKeyUtils.getPublicKeyFolder(), newFilename); try { JSch jsch=new JSch(); KeyPair kpair=KeyPair.genKeyPair(jsch, type, key_size); kpair.writePrivateKey(new FileOutputStream(newKey)); kpair.writePublicKey(new FileOutputStream(newPubKey), "sgit"); kpair.dispose(); } catch (Exception e) { //TODO e.printStackTrace(); } ((PrivateKeyManageActivity)getActivity()).refreshList(); }