File: ChangePassphrase.java

package info (click to toggle)
jsch 0.2.19-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,980 kB
  • sloc: java: 36,477; xml: 1,352; sh: 184; python: 57; makefile: 2
file content (66 lines) | stat: -rw-r--r-- 2,194 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
 * This program will demonstrate to change the passphrase for a private key file instead of creating
 * a new private key. A passphrase will be prompted if the given private-key has been encrypted.
 * After successfully loading the content of the private-key, the new passphrase will be prompted
 * and the given private-key will be re-encrypted with that new passphrase.
 */
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.KeyPair;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class ChangePassphrase {
  public static void main(String[] arg) {
    if (arg.length != 1) {
      System.err.println("usage: java ChangePassphrase private_key");
      System.exit(-1);
    }

    JSch jsch = new JSch();

    String pkey = arg[0];

    try {
      KeyPair kpair = KeyPair.load(jsch, pkey);

      System.out
          .println(pkey + " has " + (kpair.isEncrypted() ? "been " : "not been ") + "encrypted");

      String passphrase = "";
      while (kpair.isEncrypted()) {
        JTextField passphraseField = new JPasswordField(20);
        Object[] ob = {passphraseField};
        int result = JOptionPane.showConfirmDialog(null, ob, "Enter passphrase for " + pkey,
            JOptionPane.OK_CANCEL_OPTION);
        if (result != JOptionPane.OK_OPTION) {
          System.exit(-1);
        }
        passphrase = passphraseField.getText();
        if (!kpair.decrypt(passphrase)) {
          System.out.println("failed to decrypt " + pkey);
        } else {
          System.out.println(pkey + " is decrypted.");
        }
      }

      passphrase = "";

      JTextField passphraseField = new JPasswordField(20);
      Object[] ob = {passphraseField};
      int result = JOptionPane.showConfirmDialog(null, ob,
          "Enter new passphrase for " + pkey + " (empty for no passphrase)",
          JOptionPane.OK_CANCEL_OPTION);
      if (result != JOptionPane.OK_OPTION) {
        System.exit(-1);
      }
      passphrase = passphraseField.getText();

      kpair.writePrivateKey(pkey, passphrase.getBytes());
      kpair.dispose();
    } catch (Exception e) {
      System.out.println(e);
    }
    System.exit(0);
  }
}