package xxx;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.KeyPair;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
@Service
public class SSHKeyGeneratorServiceImpl implements SSHKeyGeneratorService {
private static final int KEY_SIZE = 2048;
public String generateSSHKey(SftpKeyDTO dto) {
String keyMagic = SftpKeyUtil.genRandomMagic();
KeyPair keyPair;
String priKeyFileName;
try {
keyPair = KeyPair.genKeyPair(new JSch(), KeyPair.RSA, KEY_SIZE);
keyPair.writePrivateKey(new FileOutputStream(getPriKeyFile(dto.getid())), keyMagic.getBytes(StandardCharsets.UTF_8));
keyPair.writePublicKey(new FileOutputStream(getPubKeyFile(dto.getid())), "");
} catch (Exception e) {
throw Exceptions.exception(ErrorCodeEnum.GENERATE_SSH_KEY_FAIL, e);
}
return getPublicKeyContext(keyPair);
}
private String getPublicKeyContext(KeyPair keyPair) {
byte[] pubBlob=keyPair.getPublicKeyBlob();
byte[] pub= SftpKeyUtil.toBase64(pubBlob, 0, pubBlob.length);
String result = "ssh-rsa ";
result = result + new String(pub, 0, pub.length, StandardCharsets.UTF_8);
return result;
}
private File getPriKeyFile(String id) throws IOException {
return generateFile(id, "_pri");
}
private File getPubKeyFile(String id) throws IOException {
return generateFile(id, "_pub");
}
private File generateFile(String id, String keyType) throws IOException {
String filename = id + keyType;
int index = 1;
while (true) {
File keyFile = new File(PathConstant.getKeysPath(), filename);
if (keyFile.exists()) {
filename = id + keyType + (++index);
continue;
}
if (keyFile.createNewFile()) {
return keyFile;
}
}
}
}