Hon*_*hen 3 java security openssl rsa
我有一个像这样的 RSA 公钥文件:
-----BEGIN RSA PUBLIC KEY-----
this is content
-----END RSA PUBLIC KEY-----
Run Code Online (Sandbox Code Playgroud)
我用java来阅读它:
KeyFactory factory = KeyFactory.getInstance("RSA");
KeySpec spec = new X509EncodedKeySpec(bytesFromThisFile); // bytesFromThisFile is created and filled correctly
PublicKey publicKey = factory.generatePublic(spec);
Run Code Online (Sandbox Code Playgroud)
然后我得到一个例外:
java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
Run Code Online (Sandbox Code Playgroud)
如何正确读取文件?有没有办法将此 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);
}
Run Code Online (Sandbox Code Playgroud)
来源:从文件加载 RSA 公钥
| 归档时间: |
|
| 查看次数: |
9244 次 |
| 最近记录: |