public class CallEXEUtil {
@Value("${sha256PrefixBin}")
private String sha256PrefixBin;
/**
* 执行可执行文件
* @param command 执行命令
* @throws IOException
*/
public static String execute(String command) {
String line = null;
try {
Process process = Runtime.getRuntime().exec(command);
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
System.out.println(line);
log.info(line);
}
} catch (Exception e) {
log.error("error info of execute command: {}", e);
}
return line;
}
/**
* 通过KMS进行签名
* @param toSign 要签名的串
* @return
* @throws IOException
*/
public String KMSSign(String toSign) throws IOException {
// 先判断系统类型 type 为 true 时为 Windows,否则为 Linux
String osName = System.getProperties().getProperty("os.name");
boolean type = true;
if (!osName.contains("Windows")){
type = false;
}
// 判断入参合法性
if (toSign.isEmpty()) {
return "toSign is empty";
}
// 此案先创建此模块根目录
File file = null;
if (type) {
file = new File("C:\\export\\sign");
} else {
file = new File("/tmp/sign");
}
if (!file.exists()) {
file.mkdirs();
}
// 获取 bin 中存在的内容
String sha256PrefixFileContent = sha256PrefixBin;
// 合并 bin 与 入参
byte[] sha256Prefix = Base64Util.decode(sha256PrefixFileContent);
byte[] sha256ToSign = Sha256Util.sha256(toSign);
byte[] merge = new byte[sha256ToSign.length + sha256Prefix.length];
System.arraycopy(sha256Prefix, 0, merge, 0, sha256Prefix.length);
System.arraycopy(sha256ToSign, 0, merge, sha256Prefix.length, sha256ToSign.length);
String outSignPathWin = "";
String command = "";
if (type) {
// 合并后的内容,存放在 inSign.data 文件中
String inSignPathWin = "C:\\export\\sign\\inSign.data";
FileUtils.writeBytesToFile(merge, inSignPathWin);
// kms 计算后的签名值存放在 outSign.data 中
outSignPathWin = "C:\\export\\sign\\outSign.data";
FileUtils.createNewFile(outSignPathWin);
// 拼接执行命令
command = "./kmscli.exe --sn=S-xx-IotPlatformSign-21091500 --purpose=Sign --cmd=sign --mode=fl:none --in=" + inSignPathWin + " --out=" + outSignPathWin;
} else {
String inSignPathWin = "/tmp/sign/inSign.data";
FileUtils.writeBytesToFile(merge, inSignPathWin);
outSignPathWin = "/tmp/sign/outSign.data";
FileUtils.createNewFile(outSignPathWin);
command = "./kmscli3.2.7 --sn=S-xx-IotPlatformSign-21091500 --purpose=Sign --cmd=sign --mode=fl:none --in=" + inSignPathWin + " --out=" + outSignPathWin;
}
// 执行命令,执行完签名会写到 outSign.data 中
execute(command);
// 文件中获取签名
byte[] ret = FileUtils.readFileByLines(outSignPathWin);
// 判断签名值合法性
if (ret == null) {
return "the value of sign is null!";
} else {
return Base64Util.encode(ret);
}
}
}
Java调用可执行文件
于 2022-03-02 22:12:55 首次发布