In this article, we will discuss how to load an RSA public key from a file in Java. This scenario arises when we have generated a private and public key pair using OpenSSL and want to use them in Java for digital signing and verification purposes.
We can convert the private key to PKCS8 format using OpenSSL and then load it using the following code:
<code class="java">import java.nio.file.*; import java.security.*; import java.security.spec.*; public class PrivateKeyReader { public static PrivateKey get(String filename) throws Exception { byte[] keyBytes = Files.readAllBytes(Paths.get(filename)); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory kf = KeyFactory.getInstance("RSA"); return kf.generatePrivate(spec); } }</code>
To load the public key, we need to convert it to an X509 format. Here's the code snippet:
<code class="java">import java.nio.file.*; import java.security.*; import java.security.spec.*; public class PublicKeyReader { public static PublicKey get(String filename) throws Exception { byte[] keyBytes = Files.readAllBytes(Paths.get(filename)); X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); KeyFactory kf = KeyFactory.getInstance("RSA"); return kf.generatePublic(spec); } }</code>
By following these steps, you can successfully load both your RSA public and private keys from files and use them for signing and verification operations.
The above is the detailed content of How to Load an RSA Public Key from a File in Java?. For more information, please follow other related articles on the PHP Chinese website!