2

i generated a public key file using puttyGen like this:

enter image description here

Resulting in a file with this content:

    ---- BEGIN SSH2 PUBLIC KEY ----
Comment: "rsa-key-20200116"
AAAAB3NzaC1yc2EAAAABJQAAAQEA9/jf/WH+pfOHU0j9bVYjaPHp9V1F+Tau9Pwh
Zd30m389u8dCFQqWcAYIIbAFs5eE744bdztMpIC2HbqO9hCa5AAq1U2CD0XzWUFg
H5OC9krVSuhnsU6FAJoS2zz+I4P30cuLY98Kzxt6q8pouT3fIgRAmWaKpkO/ol46
APub5ZdTTTqHwpuzOKEI0iVkd6Lsqrp98kLnwCxUV3zyecZN/YsoRRpQaMbdfCfi
kc0qKjwVRNffLk4aCPB4X0yY/EYaeLmNObCuyHqvAojM5SsoB7xlFVLfoNLtnygj
Akxty2+3MO2rsO+dl++sPMNg3EK8pfT+igB0piR2dG9LpQf9Vw==
---- END SSH2 PUBLIC KEY ----

But trying with no luck at all to load this public key from this method below:

    public static PublicKey getPublicKey(String fileName) throws Exception {
    FileReader reader = new FileReader(fileName);
    PemReader pemReader = new PemReader(reader);
    PemObject pemObj = pemReader.readPemObject();

    pemReader.close();
    X509EncodedKeySpec spec = new X509EncodedKeySpec(pemObj.getContent());
    KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
    return kf.generatePublic(spec);     
}

The PemObject resulting is always null. Followed every tutorial found, somebody help me. PemObject and PemReader are from org.bouncycastle.util.io.pem.*

Am i doing something silly?

  • 4
    Yes, as `X509EncodedKeySpec` is the key as encoded for X.509 certificates, using the `SubjectPublicKeyInfo` structure. So you either have to convert the keys to that (there are command line utilities for this) or use a SSH library to read the keys. Here is something you can try if you also have the private key: https://unix.stackexchange.com/a/310350/102011 (topmost command) – Maarten Bodewes Jan 17 '20 at 00:27
  • Thanks for your answer. I had to export my private key (from puttyGen) to "OpenSSH" and then converted my pub key to a x509 encoding through command line like this: `ssh-keygen -f private.key -e -m pkcs8 > test-pkcs8.pub` as noted in [this post](https://stackoverflow.com/questions/47816938/java-ssh-rsa-string-to-public-key). And finally could load the public key. Nevertheless, i'll like to explore the other approach, reading the keys without any conversions made at all. Do you people know any libraries that allow to do that in Java? – Ricardo Álvarez Jan 17 '20 at 16:16
  • As indicated, SSH2 capable libraries should do this. And to be honest, there is no reason to create RSA key pairs for SSH2 and then use them for something else. There are plenty of other options such as OpenSSL command line, Java's own `keytool` or even GUI's like Portecle. – Maarten Bodewes Jan 18 '20 at 00:39

0 Answers0