Couldn’t load private key(unrecognized data type) while trying import pem file generated using PKCS8Generator

ssh

I am creating a KeyPair with the below mentioned spec using java(KeyPairGenerator)

  1. OpenSSH public key format
  2. Base64 encoded DER format
  3. SSH public key file format as specified in RFC4716

The public generated is validate and the private key is stored in a pem file using PKCS8Generator is not valid.When i try to import the pem file in puttygen amd getting an error saying "couldn't load private key(unrecognized data type) ",Below is the sample code


KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048, new SecureRandom());
KeyPair kp = kpg.generateKeyPair();
Key publicKey =  kp.getPublic();

String publicKeyEncoded = "---- BEGIN SSH2 PUBLIC KEY ----" + "\n" +
                       new String(Base64.getEncoder().encode(publicKey.getEncoded())) + "\n"+
                           "---- END SSH2 PUBLIC KEY ----";


//Get Private Key and store to pem file.
Key privateKey = kp.getPrivate();
PKCS8Generator encryptorBuilder = new PKCS8Generator((PrivateKey) privateKey);
PEMWriter writer = new PEMWriter(new FileWriter(new File("D:/pk.pem")));
PemObject obj = encryptorBuilder.generate();
writer.writeObject(obj);
writer.flush();
writer.close();

Can you please help me on this.
V

Best Answer

PuTTY does not support PKCS#8 format – only "raw" PEM (PKCS#1) keys and SSH.com "RFC4716-like" private keys. (Recent versions also support the new OpenSSH "bcrypt" format.)

In other words, the file needs to have one of the following headers:

  • PuTTY-User-Key-File-2: <key_type> (PuTTY .ppk)
  • -----BEGIN RSA PRIVATE KEY-----
  • -----BEGIN DSA PRIVATE KEY-----
  • -----BEGIN EC PRIVATE KEY-----
  • ---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ---- (SSH.com)
  • -----BEGIN OPENSSH PRIVATE KEY----- (OpenSSH)

Confusingly, people use the same ".pem" extension for both PKCS#1 and PKCS#8.

(A possible reason for PuTTYgen's lack of support is that OpenSSH's ssh-keygen always writes out PKCS#1, so nobody needed PKCS#8 support until now.)