Java: write and read password based encrypted private key

给你一囗甜甜゛ 提交于 2019-12-06 12:41:40

问题


I am trying to read a password based encrypted private key from a file, but I'm getting the following exception:

java.io.IOException: DerInputStream.getLength(): lengthTag=109, too big.
at sun.security.util.DerInputStream.getLength(DerInputStream.java:561)
at sun.security.util.DerValue.init(DerValue.java:365)
at sun.security.util.DerValue.<init>(DerValue.java:294)
at javax.crypto.EncryptedPrivateKeyInfo.<init>(EncryptedPrivateKeyInfo.java:84) ...

This is how I encrypt and write to file the private key:

public static void savePrivateKeyToDisk(PrivateKey privateKey, String passord){

    try {
        // unencrypted PKCS#8 private key
        byte[] encodedPrivateKey = privateKey.getEncoded();

        String MYPBEALG = "PBEWithSHA1AndDESede";

        int count = 20;
        SecureRandom random = new SecureRandom();
        byte[] salt = new byte[8];
        random.nextBytes(salt);

        // Create PBE parameter set
        PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, count);
        PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
        SecretKeyFactory keyFac = SecretKeyFactory.getInstance(MYPBEALG);
        SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

        Cipher pbeCipher = Cipher.getInstance(MYPBEALG);

        // Initialize PBE Cipher with key and parameters
        pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);

        // Encrypt the encoded Private Key with the PBE key
        byte[] cipherText = pbeCipher.doFinal(encodedPrivateKey);

        // Now construct  PKCS #8 EncryptedPrivateKeyInfo object
        AlgorithmParameters algparms = AlgorithmParameters.getInstance(MYPBEALG);
        algparms.init(pbeParamSpec);
        EncryptedPrivateKeyInfo encinfo = new EncryptedPrivateKeyInfo(algparms, cipherText);

        // DER encoded PKCS#8 encrypted key
        byte[] encryptedPkcs8 = encinfo.getEncoded();


        File encryptedPrivate = new File(PRIVATE_KEY_FILE);

        if (encryptedPrivate.getParentFile() != null) {
            encryptedPrivate.getParentFile().mkdirs();
        }
        encryptedPrivate.createNewFile();

        ObjectOutputStream publicKeyOS = new ObjectOutputStream(
                new FileOutputStream(encryptedPrivate));
        publicKeyOS.writeObject(encryptedPkcs8);
        publicKeyOS.close();

    }
    catch (Exception e){
        e.printStackTrace();
    }
}

... and this is how I'm trying to read the encrypted private key:

public static PrivateKey getPrivateKey(String passwd){
    try {

        byte[] encodedPrivateKey = getFileBytes(PRIVATE_KEY_FILE);

        // exception thrown from here
        EncryptedPrivateKeyInfo encryptPKInfo = new EncryptedPrivateKeyInfo(encodedPrivateKey);

        Cipher cipher = Cipher.getInstance(encryptPKInfo.getAlgName());
        PBEKeySpec pbeKeySpec = new PBEKeySpec(passwd.toCharArray());
        SecretKeyFactory secFac = SecretKeyFactory.getInstance(encryptPKInfo.getAlgName());
        Key pbeKey = secFac.generateSecret(pbeKeySpec);
        AlgorithmParameters algParams = encryptPKInfo.getAlgParameters();
        cipher.init(Cipher.DECRYPT_MODE, pbeKey, algParams);
        KeySpec pkcs8KeySpec = encryptPKInfo.getKeySpec(cipher);
        KeyFactory kf = KeyFactory.getInstance(ALGORITHM);
        return kf.generatePrivate(pkcs8KeySpec);
    }
    catch (Exception e){
        e.printStackTrace();
        return null;
    }
}

... the getFileBytes method:

 private static byte[] getFileBytes(String infile){
    File f = new File(infile) ;
    int sizecontent = ((int) f.length());
    byte[] data = new byte[sizecontent];
    try
    {
        FileInputStream freader = new FileInputStream(f);
        freader.read(data, 0, sizecontent) ;
        freader.close();
        return data;
    }
    catch(IOException ioe)
    {
        System.out.println(ioe.toString());
        return null;
    }
}

It seems like the encrypted private key is not in the right format, but I save it in DER PKCS#8 format. So, the question: What is the mistake in this code?


回答1:


I guess the problem is that you write an Object, but then you read byte[] (not an Object) I would suggest that you either read the whole object and then get the required bytes or even better write byte[] directly (don't use ObjectOutputStream) and then load these bytes, eg:

FileOutputStream fos = new FileOutputStream(PRIVATE_KEY_FILE);
fos.write(myByteArray);
fos.close();

and then to retrieve it:

byte[] bytes = Files.readAllBytes(Paths.get(PRIVATE_KEY_FILE));


来源:https://stackoverflow.com/questions/34386901/java-write-and-read-password-based-encrypted-private-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!