1

I run the following code:

public class Sign {

private static final PrivateKey         priv    = Util.loadPrivate();
private static final PublicKey          pub     = Util.loadPublic();
private static final HexBinaryAdapter   adp     = new HexBinaryAdapter();

public static String sign(String in) {
    try {
        Signature sign = Signature.getInstance(Util.ALG);
        sign.initSign(priv);
        sign.update(in.getBytes());
        return adp.marshal(sign.sign());

    } catch (Exception e) {e.printStackTrace();}
    return null;
}

public static boolean verify(String data, String sign) {
    try {
        Signature verify = Signature.getInstance(Util.ALG);
        verify.initVerify(pub);
        verify.update(data.getBytes());
        return verify.verify(adp.unmarshal(sign));
    } catch (Exception e) {e.printStackTrace();}
    return false;
}

}

and the main function looks like this:

    public static void main(String[] args) {
    String in = "lala";
    String sign = Sign.sign(in);
    System.out.println(sign);
    System.out.println(Sign.verify(in, sign));
}

Everything goes well when I run it from within Eclipse (the output is "true"), but when I pack it into a jar (without the main function) and run it then the output is false.

This is how I load the keys:

    public static PrivateKey loadPrivate() {
    try {
        URLConnection con = Util.class.getResource("private.key").openConnection();
        byte[] bs = new byte[con.getContentLength()];
        con.getInputStream().read(bs);
        return KeyFactory.getInstance(ALG).generatePrivate(new PKCS8EncodedKeySpec(bs));
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

public static PublicKey loadPublic() {
    try {
        URLConnection con = Util.class.getResource("public.key").openConnection();
        byte[] bs = new byte[con.getContentLength()];
        con.getInputStream().read(bs);
        return KeyFactory.getInstance(ALG).generatePublic(new X509EncodedKeySpec(bs));
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

I checked and loading the keys works fine.

Any idea ?

Gilad
  • 538
  • 5
  • 16
  • I have a feeling the problem is the classpath. What arguments are you using to execute the main function? – Chris Thompson Apr 13 '11 at 21:30
  • Please show us the arguments to the `java` command, especially the classpath settings. The files need to be located in the classpath in order to be found. Eclipse normally handles that for you (BuildPath) but on the command line it's your turn. – Thomas Apr 13 '11 at 22:39

1 Answers1

0

Just run like this:

java Main -classpath=/path/to/libraryk.jar
Stijn Leenknegt
  • 1,317
  • 4
  • 12
  • 22