java - 如何在 java 中读取 rsa 公钥文件?
问题描述
我有一个这样的 RSA 公钥文件:
-----BEGIN RSA PUBLIC KEY-----
this is content
-----END RSA PUBLIC KEY-----
我用java来阅读它:
KeyFactory factory = KeyFactory.getInstance("RSA");
KeySpec spec = new X509EncodedKeySpec(bytesFromThisFile); // bytesFromThisFile is created and filled correctly
PublicKey publicKey = factory.generatePublic(spec);
然后我得到一个例外:
java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
如何正确读取文件?有没有办法将此 rsa 公钥文件转换为 java 可读格式?
解决方案
试试这个方法:
/**
* reads a public key from a file
* @param filename name of the file to read
* @param algorithm is usually RSA
* @return the read public key
* @throws Exception
*/
public PublicKey getPemPublicKey(String filename, String algorithm) throws Exception {
File f = new File(filename);
FileInputStream fis = new FileInputStream(f);
DataInputStream dis = new DataInputStream(fis);
byte[] keyBytes = new byte[(int) f.length()];
dis.readFully(keyBytes);
dis.close();
String temp = new String(keyBytes);
String publicKeyPEM = temp.replace("-----BEGIN PUBLIC KEY-----\n", "");
publicKeyPEM = publicKeyPEM.replace("-----END PUBLIC KEY-----", "");
BASE64Decoder b64 = new BASE64Decoder();
byte[] decoded = b64.decodeBuffer(publicKeyPEM);
X509EncodedKeySpec spec = new X509EncodedKeySpec(decoded);
KeyFactory kf = KeyFactory.getInstance(algorithm);
return kf.generatePublic(spec);
}
推荐阅读
- r - R在时间序列对象上分段,试图使其工作
- unity3d - 使用精灵进行 Unity 2D 攀爬
- javascript - JavaScript,检测鼠标光标何时不在任何元素上
- ruby-on-rails - Rails:将使用 current_user 进行分页
- reactjs - React 测试库:测试样式(特别是背景图片)
- redux - redux-persist,使用 Transform 只保存前 10 个项目
- scala.js - binding.scala 组件到字符串的转换
- javascript - 保存并加载复选框状态到文件
- python - 使用 WebSocket 的 AWS IoT MQTT:CERTIFICATE_VERIFY_FAILED
- regex - Puppet file_line 不适用于代理而不是应用