使用jar文件中的代码时出现问题

时间:2011-04-13 21:27:56

标签: java jar sha1 signature dsa

我运行以下代码:

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;
}

}

,主要功能如下:

    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));
}

当我从Eclipse中运行它(输出为“true”)时,一切顺利,但是当我将它打包到jar(没有main函数)并运行它时输出为false。

这是我加载密钥的方式:

    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;
    }
}

我检查并加载密钥工作正常。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

就像这样跑:

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