File: ChangePassphrase.java

package info (click to toggle)
jsch 0.1.51-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 1,312 kB
  • ctags: 2,540
  • sloc: java: 17,283; xml: 180; sh: 120; perl: 69; python: 54; makefile: 20
file content (73 lines) | stat: -rw-r--r-- 2,163 bytes parent folder | download | duplicates (3)
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
67
68
69
70
71
72
73
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/**
 * This program will demonstrate to change the passphrase for a
 * private key file instead of creating a new private key.
 *   $ CLASSPATH=.:../build javac ChangePassphrase.java
 *   $ CLASSPATH=.:../build java ChangePassphrase 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.*;
import javax.swing.*;

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=(JTextField)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=(JTextField)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.setPassphrase(passphrase);
      kpair.writePrivateKey(pkey);
      kpair.dispose();
    }
    catch(Exception e){
      System.out.println(e);
    }
    System.exit(0);
  }
}