我一直在使用 Java 安全 api,并遵循有关如何生成数字签名的教程:http: //docs.oracle.com/javase/tutorial/security/apisign/gensig.html
问题是当我运行代码时,即使要签名的私钥和数据保持不变,输出签名也总是不同的。我在下面提供了我曾经运行的代码。“priv”是一个保存私钥的文件,用于对数据进行签名:“hello”。
基本上,两个输出显示相同的数据:“hello”使用相同的密钥签名,但输出不同。我期望得到相同的输出。此外,当我再次运行程序时,签名数据再次与初始运行不同。任何帮助将非常感激。提前致谢
public static void main(String[] args) {
try {
FileInputStream privfis;
privfis = new FileInputStream("priv");
byte[] encKey = new byte[privfis.available()];
// obtain the encoded key in the file
privfis.read(encKey);
privfis.close();
PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec( encKey);
KeyFactory keyFactory = KeyFactory.getInstance("DSA", "SUN");
PrivateKey priv = keyFactory.generatePrivate(privKeySpec);
Signature dsa = Signature.getInstance("SHA1withDSA", "SUN");
dsa.initSign(priv);
String message = "hello";
System.out.println(getHexString(message.getBytes()));
dsa.update(message.getBytes());
byte[] realSig = dsa.sign();
System.out.println(getHexString(realSig));
dsa.update(message.getBytes());
System.out.println(getHexString(message.getBytes()));
byte[] realSig2 = dsa.sign();
System.out.println(getHexString(realSig2));
} catch (Exception e) {
System.err.println("Caught exception " + e.toString());
e.printStackTrace();
}
}
private static String getHexString(byte[] b) {
String result = "";
for (int i = 0; i < b.length; i++) {
result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
}
return result;
}
}