Java:编写和读取基于密码的加密私钥 [英] Java: write and read password based encrypted private key

查看:342
本文介绍了Java:编写和读取基于密码的加密私钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从文件中读取基于密码的加密私钥,但是我收到以下异常:

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;
    }
}

... getFileBytes方法:

... 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;
    }
}

似乎加密的私钥不在正确的格式,但我保存在DER PKCS#8格式。
所以问题:这段代码有什么错误?

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?

推荐答案

我猜问题是你写的一个对象,但是您读取 byte [] (而不是 Object
我建议您读取整个对象,然后获取所需的字节,甚至更好地直接写入 byte [] (不要使用 ObjectOutputStream ),然后加载这些字节,例如:

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();

然后检索:

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

这篇关于Java:编写和读取基于密码的加密私钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆