1 19 20 package com.sslexplorer.security.pki; 21 22 import java.io.IOException ; 23 import java.io.InputStream ; 24 import java.io.OutputStream ; 25 26 import com.sslexplorer.boot.Util; 27 28 public class SshKeyGenerator { 29 30 31 32 35 public SshKeyGenerator() { 36 } 37 38 49 public static void generateKeyPair(String type, int bits, 50 String username, String passphrase, OutputStream prvOut, OutputStream pubOut) throws IOException , InvalidKeyException { 51 52 String keyType = type; 53 54 if (keyType.equalsIgnoreCase("DSA")) { 55 keyType = "ssh-dss"; 56 } 57 58 if (keyType.equalsIgnoreCase("RSA")) { 59 keyType = "ssh-rsa"; 60 } 61 62 final SshKeyPair pair = SshKeyPairFactory.newInstance(keyType); 63 System.out.println("Generating " + String.valueOf(bits) + " bit " + 64 keyType + " key pair"); 65 66 pair.generate(bits); 67 68 SshPublicKeyFile pub = SshPublicKeyFile.create(pair.getPublicKey(), 70 new SECSHPublicKeyFormat(username, 71 String.valueOf(bits) + "-bit " + type)); 72 73 pubOut.write(pub.getBytes()); 74 Util.closeStream(pubOut); 75 76 77 SshPrivateKeyFile prv = SshPrivateKeyFile.create(pair.getPrivateKey(), 78 passphrase, 79 new SshtoolsPrivateKeyFormat(username, 80 String.valueOf(bits) + "-bit " + type)); 81 prvOut.write(prv.getBytes()); 82 Util.closeStream(prvOut); 83 } 84 85 86 96 public static void changePassphrase(InputStream prvIn, OutputStream prvOut, String oldPassphrase, 97 String newPassphrase) throws IOException , InvalidKeyException { 98 SshPrivateKeyFile file = SshPrivateKeyFile.parse(prvIn); 100 file.changePassphrase(oldPassphrase, newPassphrase); 101 102 Util.closeStream(prvIn); 103 104 try { 105 prvOut.write(file.getBytes()); 106 } finally { 107 Util.closeStream(prvOut); 108 } 109 } 110 111 112 113 114 } 115 | Popular Tags |