.jks或者.keystore转换为.pem
注意:此处主要借助于sh脚本进行转换
新建shell脚本:
前提: 需要配置好keytool、openssl命令
证书转换路径:
1、jks -> pkcs12 -> pem
2、keystore -> pkcs12 -> pem
注意:jks和keystore转换方式一致
#!/usr/bin/env bash
function keystore_2_pem() {
srckeystore=$1
srckeystorename=${srckeystore##*/}
srcstorepass=$2
tmpdir=$(mktemp -d)
cp "$srckeystore" "$tmpdir"
cd "$tmpdir" || exit
keytool -importkeystore \
-srckeystore "$srckeystore" \
-destkeystore "$srckeystorename".pkcs12 \
-deststoretype pkcs12 \
-srcstorepass "${srcstorepass}" \
-deststorepass "${srcstorepass}"
openssl pkcs12 \
-in "$srckeystorename".pkcs12 \
-out "$srckeystorename".pem \
-passin pass:"${srcstorepass}" \
-passout pass:"${srcstorepass}"
cert_info=`cat "${srckeystorename}".pem`
echo "${cert_info}"
dates=`openssl x509 -in "${srckeystorename}".pem -noout -dates`
echo "${dates}"
}
srckeystore=$1
srcstorepass=$2
keystore_2_pem "$srckeystore" "$srcstorepass"
创建Java工程:
后续会用到打包,所以此处引入 maven-assembly-plugin 打包工具,将依赖信息打包到一个jar中,方便后续java -jar 执行测试
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <executions> <execution> <phase>package</phase> <goals> <goal>single</goal> </goals> <configuration> <archive> <manifest> <mainClass> com.wd.ShellOpr // main方法类 </mainClass> </manifest> </archive> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> </configuration> </execution> </executions> </plugin> </plugins> </build>
创建java类,执行脚本:
package com.wd;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
public class ShellOpr {
public static void main(String[] args) throws Exception {
/*
sh 执行shell
cert_opr.sh 执行证书转换的脚本
/root/server.jks 待转换的证书路径
123456 证书密码
*/
String[] cmd = new String[]{"sh", "cert_opr.sh", "/root/server.jks", "123456"};
Process process = Runtime.getRuntime().exec(cmd);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
String line;
StringBuilder ans = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
ans.append(line).append(System.lineSeparator());
}
System.out.print(ans);
}
}
输出结果:
标签:srcstorepass,java,证书,srckeystore,代码,pkcs12,pem,srckeystorename From: https://www.cnblogs.com/steven-russell/p/17660480.html