JAVA: How to save a private key in a pem file with password protection

前端 未结 1 819
独厮守ぢ
独厮守ぢ 2021-02-09 09:40

I am trying to save a private key in a pem file, protected with a password. The problem is, the pem file is created and I can even open it with openssl

相关标签:
1条回答
  • 2021-02-09 10:26

    Well you should read the BouncyCastle documentation carefully. It states for the constructor you use:

    // Constructor for an unencrypted private key PEM object.
    PKCS8Generator(java.security.PrivateKey key)
    
    // Constructor for an encrypted private key PEM object.
    PKCS8Generator(java.security.PrivateKey key, java.lang.String algorithm, java.lang.String provider)
    

    Hence you are using the constructor for creating an creates an unencrypted PKCS8Generator instance. The password you set as no effect.

    Use one of the other constructors instead that create an encrypting instance according to the documentation.

    Note: The code in the question requires an outdated version of BouncyCastle (1.4x?), because the current version (1.5x) has different constructors, incompatible with those presented in this answer.


    For newer versions use:

    import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
    
    JcaPEMWriter writer = new JcaPEMWriter(new PrintWriter(System.out));
    writer.writeObject(sk);
    writer.close();
    

    possibly replacing the PrintWriter with any other Writer of course.

    0 讨论(0)
提交回复
热议问题