Java读取PEM文件格式的方法详解

PEM文件简介
PEM(Privacy-Enhanced Mail)文件是一种用于安全通信的文件格式,常用于存储公钥、私钥和证书,在Java中,我们可以使用PEM格式的文件来读取公钥、私钥或证书信息,本文将详细介绍如何在Java中读取PEM文件格式。
Java读取PEM文件的基本步骤
- 读取PEM文件内容
- 解析PEM文件内容
- 获取公钥、私钥或证书信息
读取PEM文件内容

我们需要使用Java的文件操作类来读取PEM文件的内容,以下是一个示例代码:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ReadPEMFile {
public static List<String> readFileContent(String filePath) throws IOException {
List<String> contentList = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
contentList.add(line);
}
}
return contentList;
}
}
解析PEM文件内容
读取完PEM文件内容后,我们需要解析这些内容以获取公钥、私钥或证书信息,以下是一个解析PEM文件内容的示例代码:
import java.util.List;
public class PEMParser {
public static String extractPEMContent(List<String> contentList) {
StringBuilder pemContent = new StringBuilder();
boolean inPEM = false;
for (String line : contentList) {
if (line.equals("-----BEGIN PUBLIC KEY-----")) {
inPEM = true;
} else if (line.equals("-----END PUBLIC KEY-----")) {
inPEM = false;
} else if (inPEM) {
pemContent.append(line);
}
}
return pemContent.toString();
}
}
获取公钥、私钥或证书信息

解析完PEM文件内容后,我们可以根据需要获取公钥、私钥或证书信息,以下是一个示例代码:
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class PEMReader {
public static PublicKey readPublicKey(String pemContent) throws Exception {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] encoded = pemContent.getBytes();
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encoded);
return keyFactory.generatePublic(keySpec);
}
public static PrivateKey readPrivateKey(String pemContent) throws Exception {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] encoded = pemContent.getBytes();
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
return keyFactory.generatePrivate(keySpec);
}
}
本文详细介绍了如何在Java中读取PEM文件格式,通过以上步骤,我们可以轻松地从PEM文件中获取公钥、私钥或证书信息,在实际应用中,根据需要选择合适的解析方法和获取信息的方法即可。


















