JAVA执行LINUX命令加密内容以及MAC

最近有遇到一个问题就是接口放提供的接口密文为PHP的sha256sum加密的内容
在网上找了半天没找到java相应的加密方式

最后迫不得已使用程序执行linux命令来加密
echo -n '123456bzGI9IZAaheT8LtAvhlYNnpDgwuy4hvw' | sha256sum | xxd -r -p | base64 -w0

java程序为:

public static String getSHA256Value(String password){
String result = "";
InputStream in = null;
try {
//Linux
Process pro = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c","echo -n '" + password + "' | sha256sum | xxd -r -p | base64 -w0"});
pro.waitFor();
in = pro.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in));
result = read.readLine();
if(StringUtil.isEmpty(result)){
//Mac
pro = Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","echo -n '" + password + "' | shasum -a 256 | xxd -r -p | base64 -b0"});
pro.waitFor();
in = pro.getInputStream();
read = new BufferedReader(new InputStreamReader(in));
result = read.readLine();
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}


由于mac和linux有些不一样,所以执行的命令也稍微修改了下,如上

你可能感兴趣的:(Java)