JSch getting “invalid privatekey:” while trying to load an RSA private key by KeyPairGenerator

馋奶兔 提交于 2019-11-29 07:37:24

The Sun JCA provider will return an DER-encoded unencrypted PKCS #8 structure, rather than an RSAPrivateKey object when you call PrivateKey.getEncoded().

You can use BouncyCastle to give you the key in the format you require:

import java.io.StringWriter;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.SecureRandom;

import org.bouncycastle.openssl.PEMWriter;

public class JSCH {

  public static void main(String[] args) throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(2048, new SecureRandom());
    PrivateKey privateKey = keyPairGenerator.genKeyPair().getPrivate();

    StringWriter writer = new StringWriter();

    try (PEMWriter pemWriter = new PEMWriter(writer)) {
      pemWriter.writeObject(privateKey);
    }

    String privateKeyStr = writer.toString();
    System.out.println(privateKeyStr);
    com.jcraft.jsch.KeyPair
        .load(null, privateKeyStr.getBytes("US-ASCII"), null);
  }
}

There may be a more elegant way to get the encoded key as a byte string. It feels ugly to write it as a string and call getBytes(), but perhaps you can look into this.

Example output:

-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEA3r29olF+Kul+aHsB28i9x8RiH6OEgIDoqcN4Ph0+bCYBi9lk
E/TVtLXxNxXvvcsK5DyQLZAWj/W0QmvmItndkzcWFojIoS3XT7kFPeC49hPe6g/W
ihM7eS5W3wTzAoljimyMjFUkw9ahShRrL+Dl6ZeqMW5bTwUXgcIFSKNw4iFQJFFO
5G8a1ObAV5iNA1ve5IFntKjCc5WIA4byilBCLcoXCeQNSPwyGVc1Okz22FTAQFzk
9eQthuF3AIAhHcDgf1yxx6RTTMMMSWzIva6xZvTHCKov3CwTLioH1Ri72UT9GAoq
O4hS/CL4Q4m09X6KGicXR86CpQ8TiXD4A+HwkQIDAQABAoIBAQCLYmrvz1VHnzPm
R8ti8NypzN+mctnw3Do8OcDeBcjRPntLO2+f+V9eJVjcItMSjqOzLZ7/lCI6VgRG
aGTsPC+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S9rObTkDZXsKfLJhT5x6xA6USnWC
ZPY8jO4b1RXf3v1mHpkx21dKmY2YvNetzp6OaK8DzPwFM8KUh5GG
-----END RSA PRIVATE KEY-----

You can use PEMWriter to convert your private key to PEM format that will be accepted by JSch

The following example converts a key returned from KeyStore (JKS)

Key privateKey = KeyStore.getKey(privateKeyAlias, keyStorePassword);//get key from JKS
StringWriter stringWriter = new StringWriter();
PEMWriter pemWriter = new PEMWriter(stringWriter);
pemWriter.writeObject(privateKey);
pemWriter.close();

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