2

使用 java 提取 jks 文件中的公钥和私钥

 1 year ago
source link: https://fanlumaster.github.io/2023/09/02/%E4%BD%BF%E7%94%A8-java-%E6%8F%90%E5%8F%96-jks-%E6%96%87%E4%BB%B6%E4%B8%AD%E7%9A%84%E5%85%AC%E9%92%A5%E5%92%8C%E7%A7%81%E9%92%A5/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

使用 java 提取 jks 文件中的公钥和私钥

使用 java 提取 jks 文件中的公钥和私钥 _

2023-09-02 21:20 - 2023-09-02 23:32

2.1k 字

18 分钟

注意,这个代码只能提取标准 jks 文件中的公钥和私钥,如果是使用 jdk17 中的 keytool 生成的 jks 文件,本文的代码是不生效的。

我们用 jdk17 版本的 keytool 生成的密钥库类型为 PKCS12,而 PKCS12 只有 storepass 属性,没有 keypass,因此我们单独指定密钥条目的密码,即填入的 keypass 将不会生效,签名的时候也会无法正常按照我们创建时填写的 keypass 来读取我们的密钥。

我这里使用的 jks 文件是使用 jdk8 中的 keytool 生成的。

代码写出来很简单,

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.cert.Certificate;
import java.util.Base64;

public class KeyStoreExtract {
public static void main(String[] args) {
String jksFile = "C:\\EDisk\\JavaCodes\\certificate\\jks_demo\\fanyfull.jks";
String alias = "fanyfull";
String storepass = "ffsp123456";
String keypass = "ffkp123456";

try {
FileInputStream fis = new FileInputStream(jksFile);
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(fis, storepass.toCharArray());
fis.close();

Security.addProvider(new BouncyCastleProvider());

PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, keypass.toCharArray());
Certificate cert = keyStore.getCertificate(alias);
PublicKey publicKey = cert.getPublicKey();

String base64PrivateKey = Base64.getEncoder().encodeToString(privateKey.getEncoded());
String base64Cert = Base64.getEncoder().encodeToString(cert.getEncoded());
String base64PublicKey = Base64.getEncoder().encodeToString(publicKey.getEncoded());

// public key
System.out.println("-----BEGIN PUBLIC KEY-----");
System.out.println(base64PublicKey);
System.out.println("-----END PUBLIC KEY-----");

// private key
System.out.println("-----BEGIN PRIVATE KEY-----");
System.out.println(base64PrivateKey);
System.out.println("-----END PRIVATE KEY-----");

// cert
System.out.println("-----BEGIN CERTIFICATE-----");
System.out.println(base64Cert);
System.out.println("-----END CERTIFICATE-----");
} catch (Exception e) {
e.printStackTrace();
}
}
}

1、https://www.cnblogs.com/simon-xie/p/17004614.html


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK