2020package com .cloud .utils .ssh ;
2121
2222import java .io .ByteArrayOutputStream ;
23+ import java .math .BigInteger ;
24+ import java .nio .ByteBuffer ;
25+ import java .security .KeyPair ;
2326import java .security .MessageDigest ;
2427import java .security .NoSuchAlgorithmException ;
28+ import java .security .NoSuchProviderException ;
29+ import java .security .interfaces .RSAPublicKey ;
2530
31+ import org .apache .cloudstack .utils .security .CertUtils ;
2632import org .apache .commons .codec .binary .Base64 ;
2733
28- import com .jcraft .jsch .JSch ;
29- import com .jcraft .jsch .JSchException ;
30- import com .jcraft .jsch .KeyPair ;
31-
3234public class SSHKeysHelper {
3335
3436 private KeyPair keyPair ;
@@ -45,8 +47,8 @@ private static String toHexString(byte[] b) {
4547
4648 public SSHKeysHelper (Integer keyLength ) {
4749 try {
48- keyPair = KeyPair . genKeyPair ( new JSch (), KeyPair . RSA , keyLength );
49- } catch (JSchException e ) {
50+ keyPair = CertUtils . generateRandomKeyPair ( keyLength );
51+ } catch (NoSuchAlgorithmException | NoSuchProviderException e ) {
5052 e .printStackTrace ();
5153 }
5254 }
@@ -105,17 +107,43 @@ public static String getPublicKeyFromKeyMaterial(String keyMaterial) {
105107 }
106108
107109 public String getPublicKey () {
108- ByteArrayOutputStream baos = new ByteArrayOutputStream ();
109- keyPair .writePublicKey (baos , "" );
110+ try {
111+ RSAPublicKey rsaPublicKey = (RSAPublicKey ) keyPair .getPublic ();
112+
113+ ByteArrayOutputStream buffer = new ByteArrayOutputStream ();
114+
115+ writeString (buffer ,"ssh-rsa" );
116+ writeBigInt (buffer , rsaPublicKey .getPublicExponent ());
117+ writeBigInt (buffer , rsaPublicKey .getModulus ());
110118
111- return baos .toString ();
119+ String base64 = Base64 .encodeBase64String (buffer .toByteArray ());
120+
121+ return "ssh-rsa " + base64 ;
122+ } catch (Exception e ) {
123+ e .printStackTrace ();
124+ }
125+ return null ;
112126 }
113127
114- public String getPrivateKey () {
115- ByteArrayOutputStream baos = new ByteArrayOutputStream ();
116- keyPair .writePrivateKey (baos );
128+ private static void writeString (ByteArrayOutputStream out , String str ) throws Exception {
129+ byte [] data = str .getBytes ("UTF-8" );
130+ out .write (ByteBuffer .allocate (4 ).putInt (data .length ).array ());
131+ out .write (data );
132+ }
133+
134+ private static void writeBigInt (ByteArrayOutputStream out , BigInteger value ) throws Exception {
135+ byte [] data = value .toByteArray ();
136+ out .write (ByteBuffer .allocate (4 ).putInt (data .length ).array ());
137+ out .write (data );
138+ }
117139
118- return baos .toString ();
140+ public String getPrivateKey () {
141+ try {
142+ return CertUtils .privateKeyToPem (keyPair .getPrivate ());
143+ } catch (Exception e ) {
144+ e .printStackTrace ();
145+ }
146+ return null ;
119147 }
120148
121149}
0 commit comments