View Javadoc
1   package org.kuali.common.util.ssh.impl;
2   
3   import java.io.ByteArrayOutputStream;
4   import java.io.UnsupportedEncodingException;
5   
6   import org.kuali.common.util.Assert;
7   import org.kuali.common.util.Encodings;
8   import org.kuali.common.util.ssh.api.SshService;
9   import org.kuali.common.util.ssh.model.Algorithm;
10  import org.kuali.common.util.ssh.model.GenerateKeyPairContext;
11  import org.kuali.common.util.ssh.model.KeyPair;
12  
13  import com.jcraft.jsch.JSch;
14  import com.jcraft.jsch.JSchException;
15  
16  public class DefaultSshService implements SshService {
17  
18  	private static final String UTF8 = Encodings.UTF8;
19  	private static final int DSA = com.jcraft.jsch.KeyPair.DSA;
20  	private static final int RSA = com.jcraft.jsch.KeyPair.RSA;
21  
22  	@Override
23  	public KeyPair generateKeyPair(GenerateKeyPairContext context) {
24  		Assert.noNulls(context);
25  		int algorithm = (Algorithm.DSA == context.getAlgorithm()) ? DSA : RSA;
26  		JSch jsch = new JSch();
27  		com.jcraft.jsch.KeyPair keyPair = getKeyPair(jsch, algorithm, context.getSize());
28  		String publicKey = getPublicKey(keyPair, context.getName()).trim();
29  		String privateKey = getPrivateKey(keyPair);
30  		String fingerprint = keyPair.getFingerPrint();
31  		return new KeyPair.Builder(context.getName()).publicKey(publicKey).privateKey(privateKey).fingerprint(fingerprint).build();
32  	}
33  
34  	protected com.jcraft.jsch.KeyPair getKeyPair(JSch jsch, int type, int size) {
35  		try {
36  			return com.jcraft.jsch.KeyPair.genKeyPair(jsch, type, size);
37  		} catch (JSchException e) {
38  			throw new IllegalStateException(e);
39  		}
40  	}
41  
42  	protected String getPrivateKey(com.jcraft.jsch.KeyPair keyPair) {
43  		ByteArrayOutputStream out = new ByteArrayOutputStream();
44  		keyPair.writePrivateKey(out);
45  		return toUTF8String(out);
46  	}
47  
48  	protected String getPublicKey(com.jcraft.jsch.KeyPair keyPair, String name) {
49  		ByteArrayOutputStream out = new ByteArrayOutputStream();
50  		keyPair.writePublicKey(out, name);
51  		return toUTF8String(out);
52  	}
53  
54  	protected String toUTF8String(ByteArrayOutputStream out) {
55  		try {
56  			return out.toString(UTF8);
57  		} catch (UnsupportedEncodingException e) {
58  			throw new IllegalStateException(e);
59  		}
60  	}
61  }