jks轉(zhuǎn)為p12柑营,然后再將p12轉(zhuǎn)為pem
AndroidStudio使用keystore文件對(duì)APK進(jìn)行簽名,但快應(yīng)用中要求使用PEM文件對(duì)RPK進(jìn)行簽名泊愧。
現(xiàn)有demo.jks伊磺,證書(shū)密碼為demopwd,轉(zhuǎn)換成pem之后依然使用demopwd作為密碼删咱。
方法一:使用cmd和openssl命令
提取公鑰:
切換到j(luò)ks證書(shū)的存儲(chǔ)路徑屑埋,執(zhí)行如下命令:keytool -list -rfc -keystore demo.jks -storepass demopwd
如果出現(xiàn)下圖的錯(cuò)誤提示:
那么請(qǐng)把demo.jks文件拷貝到與keytool.exe文件同目錄下,keytool在jdk的bin目錄下痰滋,拷貝之后cmd切換到bin目錄重新執(zhí)行剛才的命令
然后就能在命令行中看到打印的公鑰內(nèi)容(也即Certificate)摘能,如下圖
提取私鑰:
jks文件中的私鑰不能直接得到续崖,需要通過(guò)openssl將jks文件轉(zhuǎn)換成pkcs12格式后再進(jìn)行提取。
執(zhí)行如下命令將demo.jks文件轉(zhuǎn)換成demo.pfx文件:
keytool -v -importkeystore -srckeystore demo.jks -srcstoretype jks -srcstorepass demopwd -destkeystore demo.pfx -deststoretype pkcs12 -deststorepass demopwd -destkeypass demopwd
命令執(zhí)行完成后目錄下就會(huì)多了一個(gè)demo.pfx文件团搞。
然后严望,執(zhí)行如下命令便可以將demo.pfx的私鑰導(dǎo)出:
openssl pkcs12 -in demo.pfx -nocerts -nodes -out demo.key
輸入密碼后會(huì)生成一個(gè)demo.key文件,打開(kāi)查看內(nèi)容
方法二:通過(guò)代碼實(shí)現(xiàn)
import sun.misc.BASE64Encoder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.security.*;
import java.security.cert.Certificate;
public class CertUtil {
private FilekeystoreFile;
private StringkeyStoreType;
private char[]password;
private Stringalias;
private FileexportedFile;
public KeyPairgetPrivateKey(KeyStore keystore, String alias, char[] password) {
try {
Key key = keystore.getKey(alias, password);
if (keyinstanceof PrivateKey) {
Certificate cert = keystore.getCertificate(alias);
PublicKey publicKey = cert.getPublicKey();
return new KeyPair(publicKey, (PrivateKey) key);
}
}catch (UnrecoverableKeyException e) {
}catch (NoSuchAlgorithmException e) {
}catch (KeyStoreException e) {
}
return null;
}
public void export()throws Exception {
KeyStore keystore = KeyStore.getInstance(keyStoreType);
BASE64Encoder encoder =new BASE64Encoder();
keystore.load(new FileInputStream(keystoreFile), password);
KeyPair keyPair = getPrivateKey(keystore, alias, password);
PrivateKey privateKey = keyPair.getPrivate();
String encoded = encoder.encode(privateKey.getEncoded());
FileWriter fw =new FileWriter(exportedFile);
fw.write("----BEGIN PRIVATE KEY----\n");
fw.write(encoded);
fw.write("\n");
fw.write("----END PRIVATE KEY----\n");
Certificate cert = keystore.getCertificate(alias);
PublicKey publicKey = cert.getPublicKey();
String encoded2 = encoder.encode(publicKey.getEncoded());
fw.write("----BEGIN CERTIFICATE----\n");
fw.write(encoded2);
fw.write("\n");
fw.write("----END CERTIFICATE----\n");
fw.close();
}
public static void main(String args[])throws Exception {
CertUtil export =new CertUtil();
export.keystoreFile =new File("/F:/Program Files/filename.jks");
export.keyStoreType ="JKS";
export.password ="password".toCharArray();
export.alias ="alias";
export.exportedFile =new File("output");
export.export();
}
}