0

I followed following steps from OpenSSL: Generating an RSA Key From the Command Line.

1. openssl genrsa -des3 -out private.pem 2048 2. openssl rsa -in private.pem -outform PEM -pubout -out public.pem 3. openssl rsa -in private.pem -out private_unencrypted.pem -outform PEM 

Now I wanted to read those files using Java code. So write the following code, as per link below code is correct but the file format which I created using above three commands casing the problem. Could anyone please guide me on this?

public class PublicPrivateKeyDemo { private static File privateKeyFile = null; private static File publicKeyFile = null; public static void main(String[] args) { String path = "E:/Advance Java/AJAX/1"; privateKeyFile = new File(path + "/" + "private.pem"); publicKeyFile = new File(path + "/" + "public.pem"); try { loadkeys(); } catch (IOException | GeneralSecurityException e) { System.out.println(e.getMessage()); } } private static void loadkeys() throws IOException, GeneralSecurityException { byte[] publicKeyBytes = new byte[(int) publicKeyFile.length()]; FileInputStream publicFis = null; publicFis = new FileInputStream(publicKeyFile); if (publicFis.read(publicKeyBytes) > 0) { X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes); KeyFactory factory = KeyFactory.getInstance("RSA"); RSAPublicKey pubKey = (RSAPublicKey) factory.generatePublic(publicKeySpec); BigInteger pKeyModulus = pubKey.getModulus(); BigInteger pKeyExponent = pubKey.getPublicExponent(); System.out.println("PUBLIC KEY EXPO : "+pKeyExponent); } byte[] privateKeyBytes = new byte[(int) privateKeyFile.length()]; FileInputStream privateFis = null; privateFis = new FileInputStream(privateKeyFile); if (privateFis.read(privateKeyBytes) > 0) { PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(privateKeyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); RSAPrivateKey privKey = (RSAPrivateKey) keyFactory.generatePrivate(spec); BigInteger pKeyModulus = privKey.getModulus(); BigInteger pKeyExponent = privKey.getPrivateExponent(); System.out.println("PRIVATE KEY : "+pKeyExponent); } } } 
2

0