Skip to content

Instantly share code, notes, and snippets.

@innovatorCho
Created August 14, 2019 05:36
Show Gist options
  • Select an option

  • Save innovatorCho/1eaf3f89c530e011a1c241c4817f6289 to your computer and use it in GitHub Desktop.

Select an option

Save innovatorCho/1eaf3f89c530e011a1c241c4817f6289 to your computer and use it in GitHub Desktop.
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.jcraft.jsch.JSch;
public class JschTemp209 {
int KEY_SIZE = 2048;
int KEY_TYPE = com.jcraft.jsch.KeyPair.RSA;
public static void main(String[] args) {
JschTemp209 work = new JschTemp209();
String filePath = "/tmp/jsch/";
try {
Map<String, String> keyMap = work.sshKeypairToJsh();
String privKey = (String)keyMap.get("PRIV_KEY");
String pubKey = (String)keyMap.get("PUB_KEY");
System.out.println("## PRIV_KEY : " + privKey);
System.out.println("##PUB_KEY : " + pubKey);
String privKeyFullPath = filePath +"priv_"+System.currentTimeMillis()+".pem";
String pubKeyFullPath = filePath +"pub_"+System.currentTimeMillis()+".pem";
work.createSshKeyFileJsch(privKeyFullPath , privKey);
work.createSshKeyFileJsch(pubKeyFullPath , pubKey);
}catch(Exception e) {
e.printStackTrace();
}
}
/*
* 키생성
* */
private Map<String, String> sshKeypairToJsh() throws Exception{
Map<String, String> map = new HashMap<String, String>();
ByteArrayOutputStream bytePrivateKey = new ByteArrayOutputStream(); // 개인키
ByteArrayOutputStream bytePublicKey = new ByteArrayOutputStream(); // 공개키
JSch jsch = new JSch();
String comment = "";
com.jcraft.jsch.KeyPair kpair = com.jcraft.jsch.KeyPair.genKeyPair(jsch, KEY_TYPE, KEY_SIZE);
kpair.writePrivateKey(bytePrivateKey);
kpair.writePublicKey(bytePublicKey, comment);
/*
* 생성한 개인키와 공개키를 Map으로 저장
* */
map.put("PRIV_KEY", bytePrivateKey.toString());
map.put("PUB_KEY", bytePublicKey.toString());
kpair.dispose();
return map;
}
/*
* 키 파일 저장
* */
private boolean createSshKeyFileJsch(String filePath, String privateKeyString) {
boolean isCreate = true;
File file = new File(filePath);
try {
FileOutputStream fos = new FileOutputStream(file);
ByteArrayOutputStream bPriv = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bPriv);
dos.write(privateKeyString.getBytes());
bPriv.close();
bPriv.flush();
fos.write(bPriv.toByteArray());
fos.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
isCreate = false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
isCreate = false;
} finally {
}
return isCreate;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment