In addition to supporting generating public key and private key, Java also supports us to convert these public key and private key files to Java objects. We just need to know the data format used in these files!
First, you need to read these files and convert their contents to byte arrays. My example with private key is as follows:
1 2 |
Path path = Paths.get("/Users/Khanh/Documents/huongdanjava.key"); byte[] bytes = Files.readAllBytes(path); |
Then, depending on the data format of the public key and private key files, we use the appropriate KeySpec objects to read the contents of these files.
For example, my public key uses the X.509 format and the private key uses the PKCS#8 format, I will code as follows:
For public key:
1 2 3 |
X509EncodedKeySpec ks = new X509EncodedKeySpec(bytes); KeyFactory kf = KeyFactory.getInstance("RSA"); PublicKey pub = kf.generatePublic(ks); |
For private key:
1 2 3 |
PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(bytes); KeyFactory kf = KeyFactory.getInstance("RSA"); PrivateKey pvt = kf.generatePrivate(ks); |
My entire code for the public key is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package com.huongdanjava.javaexample; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.X509EncodedKeySpec; public class Example { public static void main(String[] args) throws NoSuchAlgorithmException, IOException, InvalidKeySpecException { Path path = Paths.get("/Users/Khanh/Documents/huongdanjava.pub"); byte[] bytes = Files.readAllBytes(path); X509EncodedKeySpec ks = new X509EncodedKeySpec(bytes); KeyFactory kf = KeyFactory.getInstance("RSA"); PublicKey pub = kf.generatePublic(ks); System.out.println(pub.getAlgorithm()); System.out.println(pub.getFormat()); } } |
Result:
and private key:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package com.huongdanjava.javaexample; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; public class Example { public static void main(String[] args) throws NoSuchAlgorithmException, IOException, InvalidKeySpecException { Path path = Paths.get("/Users/Khanh/Documents/huongdanjava.key"); byte[] bytes = Files.readAllBytes(path); PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(bytes); KeyFactory kf = KeyFactory.getInstance("RSA"); PrivateKey pvt = kf.generatePrivate(ks); System.out.println(pvt.getAlgorithm()); System.out.println(pvt.getFormat()); } } |
Result: