27

I'm currently working on a way to convert keys into strings and vice versa. It works for the public key conversions, and converts a private key into a String. For some reason the same code won't convert a String back into a private key, which I just can't figure out.

The converter code is:

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

@SuppressWarnings("restriction")
public  class KeyConvert {


public static PublicKey stringToPublicKey(String s) {

    BASE64Decoder decoder = new BASE64Decoder();

    byte[] c = null;
    KeyFactory keyFact = null;
    PublicKey returnKey = null;

    try {
        c = decoder.decodeBuffer(s);
        keyFact = KeyFactory.getInstance("DSA", "SUN");
    } catch (Exception e) {
        System.out.println("Error in Keygen");
        e.printStackTrace();
    }


    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(c);
    try {
        returnKey = keyFact.generatePublic(x509KeySpec);
    } catch (Exception e) {

        System.out.println("Error in Keygen2");
        e.printStackTrace();

    }

    return returnKey; 

}
public static PrivateKey stringToPrivateKey(String s) {

    BASE64Decoder decoder = new BASE64Decoder();
    byte[] c = null;
    KeyFactory keyFact = null;
    PrivateKey returnKey = null;

    try {

                    c = decoder.decodeBuffer(s);
        keyFact = KeyFactory.getInstance("DSA", "SUN");
    } catch (Exception e) {

        System.out.println("Error in first try catch of stringToPrivateKey");
        e.printStackTrace();
    }


    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(c);
    try {   //the next line causes the crash
        returnKey = keyFact.generatePrivate(x509KeySpec);
    } catch (Exception e) {

        System.out.println("Error in stringToPrivateKey");
        e.printStackTrace();
    }

    return returnKey; 

}

public static String publicKeyToString(PublicKey p) {

    byte[] publicKeyBytes = p.getEncoded();
    BASE64Encoder encoder = new BASE64Encoder();
    return encoder.encode(publicKeyBytes);

}
public static String privateKeyToString(PrivateKey p) {

    byte[] privateKeyBytes = p.getEncoded();
    BASE64Encoder encoder = new BASE64Encoder();
    return encoder.encode(privateKeyBytes);
}
}

And the driver code I'm using is:

import java.security.PrivateKey;
import java.security.PublicKey;

public class SQLServerTest {
public static void main(String[] args) throws Exception {


    ServerSQLManager s = new ServerSQLManager();
    ServerUser user = new ServerUser("testUser", "pass123");
    s.getKeys(user);


    PublicKey testKey = user.getPublicKey();
    System.out.println(testKey);
    PrivateKey testKey2 = user.getPrivateKey();
    System.out.println(testKey2);
}
}

When I run this, I get an inappropriate key specification, can anyone point me in the right direction with this? The console output is:

Error in stringToPrivateKey


java.security.spec.InvalidKeySpecException: Inappropriate key specification
at sun.security.provider.DSAKeyFactory.engineGeneratePrivate(Unknown Source)
at java.security.KeyFactory.generatePrivate(Unknown Source)
at KeyConvert.stringToPrivateKey(KeyConvert.java:61)
at ServerSQLManager.getKeys(ServerSQLManager.java:128)
at SQLServerTest.main(SQLServerTest.java:20)

Sun DSA Public Key
     Parameters:DSA
    p:     fd7f5381 1d751229 52df4a9c 2eece4e7 f611b752 3cef4400 c31e3f80 b6512669
    455d4022 51fb593d 8d58fabf c5f5ba30 f6cb9b55 6cd7813b 801d346f f26660b7
    6b9950a5 a49f9fe8 047b1022 c24fbba9 d7feb7c6 1bf83b57 e7c6a8a6 150f04fb
    83f6d3c5 1ec30235 54135a16 9132f675 f3ae2b61 d72aeff2 2203199d d14801c7
q:     9760508f 15230bcc b292b982 a2eb840b f0581cf5
g:     f7e1a085 d69b3dde cbbcab5c 36b857b9 7994afbb fa3aea82 f9574c0b 3d078267
    5159578e bad4594f e6710710 8180b449 167123e8 4c281613 b7cf0932 8cc8a6e1
    3c167a8b 547c8d28 e0a3ae1e 2bb3a675 916ea37f 0bfa2135 62f1fb62 7a01243b
    cca4f1be a8519089 a883dfe1 5ae59f06 928b665e 807b5525 64014c3b fecf492a

    y:
    5210e849 24d90208 56802887 dfaededf 78d3e6d0 d2e59a1c fb52dde8 96147784
    b2589365 2529414c 8265b61d c1fe6d98 cee0eea3 cce1e366 cd621ca7 41e3a94f
    9c15bfcb eb860d19 21efd574 79bb5b15 8159b1cb e3fc7f76 f85a6fc1 8d65afc6
    7c4fafda 503b01b5 99752ee4 2408ad80 1d983579 b00e2120 6d735874 ccaea1c0

null

I'm aware I shouldn't be using the sun.misc.* library, and we're looking into the Apache version, but would still like to figure this out (also it will never be production code)

Any advice appreciated.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
  • Don't do this. String is not a container for binary data. – user207421 Mar 18 '12 at 01:12
  • Have you tried to debug this to narrow down the cause of this? Nobody here is going to debug your code for you when you just dump all your files. – Jochen Mar 18 '12 at 01:13

1 Answers1

59

Public keys are stored using a X509EncodedKeySpec as you have, but Private keys use the PKCS8EncodedKeySpec. For example like this:

public static PrivateKey loadPrivateKey(String key64) throws GeneralSecurityException {
    byte[] clear = base64Decode(key64);
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(clear);
    KeyFactory fact = KeyFactory.getInstance("DSA");
    PrivateKey priv = fact.generatePrivate(keySpec);
    Arrays.fill(clear, (byte) 0);
    return priv;
}


public static PublicKey loadPublicKey(String stored) throws GeneralSecurityException {
    byte[] data = base64Decode(stored);
    X509EncodedKeySpec spec = new X509EncodedKeySpec(data);
    KeyFactory fact = KeyFactory.getInstance("DSA");
    return fact.generatePublic(spec);
}

public static String savePrivateKey(PrivateKey priv) throws GeneralSecurityException {
    KeyFactory fact = KeyFactory.getInstance("DSA");
    PKCS8EncodedKeySpec spec = fact.getKeySpec(priv,
            PKCS8EncodedKeySpec.class);
    byte[] packed = spec.getEncoded();
    String key64 = base64Encode(packed);

    Arrays.fill(packed, (byte) 0);
    return key64;
}


public static String savePublicKey(PublicKey publ) throws GeneralSecurityException {
    KeyFactory fact = KeyFactory.getInstance("DSA");
    X509EncodedKeySpec spec = fact.getKeySpec(publ,
            X509EncodedKeySpec.class);
    return base64Encode(spec.getEncoded());
}


public static void main(String[] args) throws Exception {
    KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA");
    KeyPair pair = gen.generateKeyPair();

    String pubKey = savePublicKey(pair.getPublic());
    PublicKey pubSaved = loadPublicKey(pubKey);
    System.out.println(pair.getPublic()+"\n"+pubSaved);

    String privKey = savePrivateKey(pair.getPrivate());
    PrivateKey privSaved = loadPrivateKey(privKey);
    System.out.println(pair.getPrivate()+"\n"+privSaved);
}
Simon G.
  • 6,587
  • 25
  • 30
  • The PKCS8EncodedKeySpec is the trick. Unfortunately Sun's/Oracle's tutorial is wrong. – Peter Kriens Aug 02 '12 at 14:13
  • Is this still a valid answer? When I do the loadPrivateKey(String key) method I get the following error: java.security.spec.InvalidKeySpecException: Inappropriate key specification: DER input, Integer tag error – Juan Carlos Apr 21 '17 at 22:27
  • 1
    @JuanCarlos It is still valid. That error message implies that the private key you are reading is not precisely what you think it is. This code expects a private key encoded using ASN.1 Distinguished Encoding Rules (DER). If the input is PEM format, or has added text around the private key, it will not work. – Simon G. May 07 '17 at 23:59
  • Precsisely what you need to write a Key Generator – Sam Ginrich Dec 04 '21 at 18:33