开发者

Problem when using code from a jar file

开发者 https://www.devze.com 2023-02-24 06:09 出处:网络
I run the following code: public class Sign { private static final PrivateKeypriv= Util.loadPrivate(); private static final PublicKeypub= Util.loadPublic();

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 ?


Just run like this:

java Main -classpath=/path/to/libraryk.jar
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号