Searching...
Thursday, March 24, 2016

Loading private key from pkcs#8 file(.pem)

In Public key Cryptography (RSA) we use pair of public and private keys to encrypt and decrypt messages.

If  Alice want to send message to Bob ,Alice need Bob's public key to encrypt and Bob will decrypt message by using his private key,Bob need not to share his private key and vice versa.

In this post we will see how to load private key (pkcs#8 standard) from .pem file 

step 1:load byte[] from .pem file

       File file = new File("/home/usr/myprivatekey.pem");
        byte[] encodedKey = new byte[(int) file.length()];
FileInputStream stream = new FileInputStream(file);
stream.read(encodedKey);

step 2:Remove "-----BEGIN PRIVATE KEY-----","-----END PRIVATE KEY-----" from String

   String tempPrivateKey = new String(encodedKey);
      tempPrivateKey = tempPrivateKey.replace("-----BEGIN PRIVATE KEY-----", "");
      tempPrivateKey = tempPrivateKey.replace("-----END PRIVATE KEY-----", "");
      byte[] privateKeyArry = Base64.decodeBase64(tempPrivateKey.getBytes());

step 3: use java.security.spec.PKCS8EncodedKeySpec to load private key

       PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(privateKeyArry);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(spec);

Public keys will be X509 standard we can load using java.security.cert.CertificateFactory

0 comments:

Post a Comment

 
Back to top!