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
精彩评论