php,本身是没有函数可以生成JKS的,这就给很多PHP程序员伙伴困扰,我也是经过大量的实践也找到解决方案:
1,先利用java生成一个.jar文件,java代码如下
package javatest; // 包名
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.Key;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.util.Enumeration;
public class ConventPFXToJKS {
public static final String PKCS12 = "PKCS12";
public static final String JKS = "JKS";
public static void coverTokeyStore(String PFX_KEYSTORE_FILE,String PFX_PASSWORD,String JKS_KEYSTORE_FILE,String JKS_PASSWORD) { //这里的4个参数是从PHP中传过来的
FileInputStream fis = null;
FileOutputStream out = null;
try {
KeyStore inputKeyStore = KeyStore.getInstance("PKCS12");
fis = new FileInputStream(PFX_KEYSTORE_FILE);
char[] pfxPassword = null;
if ((PFX_PASSWORD == null) || PFX_PASSWORD.trim().equals("")) {
pfxPassword = null;
} else {
pfxPassword = PFX_PASSWORD.toCharArray();
}
char[] jksPassword = null;
if ((JKS_PASSWORD == null) || JKS_PASSWORD.trim().equals("")) {
jksPassword = null;
} else {
jksPassword = JKS_PASSWORD.toCharArray();
}
inputKeyStore.load(fis, pfxPassword);
fis.close();
KeyStore outputKeyStore = KeyStore.getInstance("JKS");
outputKeyStore.load(null, jksPassword);
Enumeration<String> enums = inputKeyStore.aliases();
while (enums.hasMoreElements()) { // we are readin just one
// certificate.
String keyAlias = (String) enums.nextElement();
System.out.println("alias=[" + keyAlias + "]");
if (inputKeyStore.isKeyEntry(keyAlias)) {
Key key = inputKeyStore.getKey(keyAlias, pfxPassword);
Certificate[] certChain = inputKeyStore.getCertificateChain(keyAlias);
outputKeyStore.setKeyEntry(keyAlias, key, jksPassword, certChain);
}
}
out = new FileOutputStream(JKS_KEYSTORE_FILE);
outputKeyStore.store(out, jksPassword);
out.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
coverTokeyStore(args[0],args[1],args[2],args[3]); // pfx to jks
}
}
把该代码生成 .jar文件
2,用PHP代码执行这个jar文件
$pkcsPass=“pfx密码”;
$jksPass="jks密码";
$pfxurl="pfx证书路径";
$jksurl="jks证书生成路径";
$jarurl="D:\wwwroot\ConventPFXToJKS.jar";
$command="java -jar ".$jarurl." ".$pfxurl." ".$pkcsPass." ".$jksurl." ".$jksPass;
exec($command,$array);
通过以上步骤完美实现pfx转jks