Java读取PKCS8格式私钥文件
byte[] buffer = Base64.getDecoder().decode(readRsaFileBody("pkcs8_rsa_private_key.pem"));
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
System.out.println(String.format(
"算法:%s\n" +
"格式:%s\n",
privateKey.getAlgorithm(),
privateKey.getFormat()
));
Java读取X509格式公钥文件
byte[] buffer = Base64.getDecoder().decode(readRsaFileBody("rsa_public_key.pem"));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
PublicKey publicKey = keyFactory.generatePublic(keySpec);
System.out.println(String.format(
"算法:%s\n" +
"格式:%s\n",
publicKey.getAlgorithm(),
publicKey.getFormat()
));
公钥加密输出Base64编码
byte[] buffer = Base64.getDecoder().decode(readRsaFileBody("rsa_public_key.pem"));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
PublicKey publicKey = keyFactory.generatePublic(keySpec);
Cipher cipher = Cipher.getInstance("RSA");
//私钥加密同理,将 publicKey 替换成 privateKey
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
String data = "12345678";
byte[] output = cipher.doFinal(data.getBytes());
String encryptData = Base64.getEncoder().encodeToString(output);
System.out.println(String.format("%s\n=>ENCRYPT,Base64=>\n%s", data, encryptData));
私钥解密
byte[] buffer = Base64.getDecoder().decode(readRsaFileBody("pkcs8_rsa_private_key.pem"));
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
Cipher cipher = Cipher.getInstance("RSA");
//公钥解密同理,将 privateKey 替换成 publicKey
cipher.init(Cipher.DECRYPT_MODE, privateKey);
//12345678
String encryptData = "UF8CW4ovruUM9ot+G3tG5DFGtDs2h3x6YOuUnK9WIz39w5W9/i7aUyi5kmMISharTg7YV9DNBzD/Zv29CZFA0acN5fejz9vXKeR4Dn50WU0ZU3yF9RuVbi2tqvpjShF6sM88ETblt9cdDty0agYBN+p0eWX1kvF/2m+TEGw4IXI=";
byte[] output = cipher.doFinal(Base64.getDecoder().decode(encryptData));
String data = new String(output);
System.out.println(String.format("%s\n=>DECRYPT=>\n%s", encryptData, data));
其他相关代码示例
public static byte[] file2bytes(String path) throws Exception {
URL resource = SslTest.class.getClassLoader().getResource(path);
return Files.readAllBytes(Paths.get(resource.toURI()));
}
public static String file2str(String path) throws Exception {
return new String(file2bytes(path));
}
/**
* 返回body去掉首尾行和换行字符
*
* @param name
* @return
* @throws Exception
*/
public static String readRsaFileBody(String name) throws Exception {
String content = file2str(name);
//tip: Base64.getDecoder() and Base64.getEncoder() 编码字符串中不包含换行字符
//tip: Base64.getMimeDecoder() and Base64.getMimeEncoder() 支持编码字符串中包含换行字符
return Arrays.stream(content.split("\r\n|\n")).filter(line -> !line.startsWith("-----")).collect(Collectors.joining(""));
}
public static InputStream file2Stream(String name) throws Exception {
return SslTest.class.getClassLoader().getResourceAsStream(name);
}
@Test
public void _read_file() throws Exception {
System.out.println(readRsaFileBody("rsa_private_key.pem"));
byte[] encode = Base64.getEncoder().encode("123456".getBytes());
byte[] decode = Base64.getMimeDecoder().decode(readRsaFileBody("rsa_private_key.pem"));
System.out.println(decode.length);
}
Reference
openssl-and-keytool-example