encryption - Read a Private Encrypted Key in Java -


i have following piece of code:

    pemparser pemparser;     file telexuskeys = new file(locationkey);     if(telexuskeys.exists())         pemparser = new pemparser(new filereader(telexuskeys));     else{         usage(ops);         throw new filenotfoundexception("the key file (company's certificate) doesn't exist!");     }      system.out.println("loading company's certificate");      object object = pemparser.readobject();     object object2 = pemparser.readobject();      pemdecryptorprovider decprov = new jcepemdecryptorproviderbuilder().build(passwordpem.tochararray());     jcapemkeyconverter converter = new jcapemkeyconverter().setprovider("bc");       byte[] keybytes = privatekeyinfo.getinstance(object2).getencoded();     pkcs8encodedkeyspec spec = new pkcs8encodedkeyspec(keybytes);     keyfactory kf = keyfactory.getinstance("rsa", "bc");             privatekey pk = kf.generateprivate(spec); 

my pem file have certificate , private key. used able read file , obtain private key file protected (encrypted) password. instruction i'm still missing. know need use pemdecryptorprovider , jcapemkeyconverter objects in order obtain haven't found correct combination.

the following code work me. (using bcpkix , bcprov libs bouncy castle).

private privatekey readprivatekey(string privatekeypath, string keypassword) throws ioexception {      filereader filereader = new filereader(privatekeypath);     pemparser keyreader = new pemparser(filereader);      jcapemkeyconverter converter = new jcapemkeyconverter();     pemdecryptorprovider decryptionprov = new jcepemdecryptorproviderbuilder().build(keypassword.tochararray());      object keypair = keyreader.readobject();     privatekeyinfo keyinfo;      if (keypair instanceof pemencryptedkeypair) {         pemkeypair decryptedkeypair = ((pemencryptedkeypair) keypair).decryptkeypair(decryptionprov);         keyinfo = decryptedkeypair.getprivatekeyinfo();     } else {         keyinfo = ((pemkeypair) keypair).getprivatekeyinfo();     }      keyreader.close();     return converter.getprivatekey(keyinfo); 

Comments