Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

bouncycastle - How to read a password encrypted key with java?

I have private key stored in file in PKCS8 DER format and protected by password. What is the easiest way to read it?

Here is the code I use to load unencrypted one:

InputStream in = new FileInputStream(privateKeyFilename);
byte[] privateKeydata = new byte[in.available()];
in.read(privateKeydata);
in.close();
KeyFactory privateKeyFactory = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec encodedKeySpec = new PKCS8EncodedKeySpec(privateKeydata);
PrivateKey privateKey = privateKeyFactory.generatePrivate(encodedKeySpec);

It works fine for unencrypted keys with the same specification. By the way, I am using BouncyCastle.

I can view this private key using following openssl command

openssl pkcs8 -in ./privatekey.key -inform DER -passin pass:thisismypass

Please, Help!!!

I,ve posted some solutions in my own answer to this topic. But I keep question unanswered in case anybody can help with making it work without extra library, just BouncyCastle.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I found the solution! Maybe its not so elegant, but... Here I will post two solutions:

  1. Prefferable, but not working
  2. Working one, but requires additional library

First:

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

Second:

And following this http://juliusdavies.ca/commons-ssl/pkcs8.html you can read about the second, working solution


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...