public static PrivateKey privateKeyFromPkcs8(String privateKeyPem) throws IOException {
  StringReader reader=new StringReader(privateKeyPem);
  Section section=PemReader.readFirstSectionAndClose(reader,PRIVATE_KEY);
  if (section == null) {
    throw new IOException("Invalid PKCS8 data.");
  }
  try {
    byte[] decodedKey=section.getBase64DecodedBytes();
    PKCS8EncodedKeySpec keySpec=new PKCS8EncodedKeySpec(decodedKey);
    KeyFactory keyFactory=SecurityUtils.getRsaKeyFactory();
    return keyFactory.generatePrivate(keySpec);
  }
 catch (  Exception e) {
    throw new IOException("Unexpected exception reading PKCS data",e);
  }
}

public static PrivateKey privateKeyFromPkcs8 ( String privateKeyPem ) throws IOException { StringReader reader = new StringReader ( privateKeyPem ) ; Section section = PemReader . readFirstSectionAndClose ( reader , PRIVATE_KEY ) ; if ( section == null ) { throw new IOException ( "Invalid PKCS8 data." ) ; } try { byte [ ] decodedKey = section . getBase64DecodedBytes ( ) ; PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec ( decodedKey ) ; KeyFactory keyFactory = SecurityUtils . getRsaKeyFactory ( ) ; return keyFactory . generatePrivate ( keySpec ) ; } catch ( Exception e ) { throw new IOException ( "Unexpected exception reading PKCS data" , e ) ; } }
the method validates an input string of private key and generate a java privatekey object . the method is non - blocking .
