I found the solution! Maybe its not so elegant, but...
Here I will post two solutions:
- Prefferable, but not working
- Working one, but requires additional library
======================== 1 ===============================
I found a kind of solution here, but it throws exception
solution:
import java.io.*;
import java.security.*;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;
/*
* This class demonstrates how to import an encrypted RSA private key as
* generated by openssl. The input file is presumed to be in DER
* format.
*/
public class ImportEncryptedPrivateKey
{
public static byte[] readPK8FromFile(String fileName) throws IOException
{
File f = new File(fileName);
DataInputStream dis = new DataInputStream(new FileInputStream(f));
byte[] theData = new byte[(int) f.length()];
dis.readFully(theData);
return theData;
}
public static void main(String[] args) throws IOException,
NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeySpecException, InvalidKeyException,
InvalidAlgorithmParameterException
{
byte[] encryptedPKInfo = readPK8FromFile("rsapriv.pk8");
EncryptedPrivateKeyInfo ePKInfo = new EncryptedPrivateKeyInfo(
encryptedPKInfo);
char[] password = { 'p', 'a', 's', 's', 'w', 'o', 'r', 'd' };
Cipher cipher = Cipher.getInstance(ePKInfo.getAlgName());
PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
// Now create the Key from the PBEKeySpec
SecretKeyFactory skFac = SecretKeyFactory.getInstance(ePKInfo
.getAlgName());
Key pbeKey = skFac.generateSecret(pbeKeySpec);
// Extract the iteration count and the salt
AlgorithmParameters algParams = ePKInfo.getAlgParameters();
cipher.init(Cipher.DECRYPT_MODE, pbeKey, algParams);
// Decrypt the encryped private key into a PKCS8EncodedKeySpec
KeySpec pkcs8KeySpec = ePKInfo.getKeySpec(cipher);
// Now retrieve the RSA Public and private keys by using an
// RSA keyfactory.
KeyFactory rsaKeyFac = KeyFactory.getInstance("RSA");
// First get the private key
RSAPrivateCrtKey rsaPriv = (RSAPrivateCrtKey) rsaKeyFac.generatePrivate(pkcs8KeySpec);
// Now derive the RSA public key from the private key
RSAPublicKeySpec rsaPubKeySpec = new RSAPublicKeySpec(rsaPriv.getModulus(), rsaPriv.getPublicExponent());
RSAPublicKey rsaPubKey = (RSAPublicKey) rsaKeyFac.generatePublic(rsaPubKeySpec);
}
}
And my exception:
Exception in thread "main" java.security.NoSuchAlgorithmException: No such algorithm: 1.2.840.113549.1.5.13
==========================================================
======================== 2 ===============================
And following this http://juliusdavies.ca/commons-ssl/pkcs8.html you can read about the second, working solution
=========================================================