从keystore中导出私钥key

生成死要key
特别需要注意的是,私钥是无法从证书库中导出的,因为那样非常不安全。如果你特别需要私钥或是私钥字符串,只能考虑用编程的方式从密钥库文件中去获取了。
由于jdk命令无法生成key,所以需要用代码从keystore文件中读取私钥base64编码数据

package test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
【从keystore中导出私钥key】
import sun.misc.BASE64Encoder;

publicclass SllKeyStore {
private File keystoreFile;
private String keyStoreType;
privatechar[] password;
private String alias;
private File exportedFile;

publicstatic 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();
returnnew KeyPair(publicKey, (PrivateKey) key);
}
} catch (UnrecoverableKeyException e) {
} catch (NoSuchAlgorithmException e) {
} catch (KeyStoreException e) {
}
returnnull;
}

publicvoid export() throws Exception {
KeyStore keystore = KeyStore.getInstance(keyStoreType);
BASE64Encoderencoder = 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 RSA PRIVATE KEY-----\r\n"); //私钥库文件必须以此开头,否则使用时会出错
fw.write(encoded);
fw.write("\r\n-----END RSA PRIVATE KEY-----"); //私钥库文件必须以此结尾
fw.close();

}

publicstaticvoid main(String args[]) throws Exception {
SllKeyStore export = new SllKeyStore();
export.keystoreFile = new File("E:/software/ssl/test.keystore"); //读取秘钥库keystore文件
export.keyStoreType = KeyStore.getDefaultType();
String passwordString = "123321"; //秘钥库口令
export.password = passwordString.toCharArray();
export.alias = "testalias"; //秘钥库别名
export.exportedFile = new File("E:/software/ssl/test.key"); //生成的私钥文件
export.export();
}
}
生成结果:此test.key为私钥,在nginx配置https中会用到
从keystore中导出私钥key
文章图片


    推荐阅读