我无法理解为什么下面的代码会在检查时返回false
?
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.Signature;
import java.security.SignatureException;
import java.security.NoSuchProviderException;
import java.security.*;
public class HelloWorld
{
public static void main(String[] args)
{
KeyPair keyPair;
String data = "test";
try {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DSA");
keyPairGen.initialize(512);
keyPair = keyPairGen.genKeyPair();
Signature sign = Signature.getInstance("SHA1withDSA", "SUN");
sign.initSign(keyPair.getPrivate());
sign.update(data.getBytes());
byte[] encoded = sign.sign();
sign = Signature.getInstance("SHA1withDSA", "SUN");
sign.initVerify(keyPair.getPublic());
sign.update(encoded);
System.out.println("Checked: " + sign.verify(encoded)); // Testing with itself returns false????
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
} catch (SignatureException ex) {
ex.printStackTrace();
} catch (NoSuchProviderException ex) {
ex.printStackTrace();
} catch (InvalidKeyException ex) {
ex.printStackTrace();
}
}
}
私钥/公钥有问题吗? 我真的很困惑。
答案 0 :(得分:1)
您正在更新错误的内容,请更改此行
sign.update(encoded);
到这个
sign.update(data.getBytes());
获取PublicKey后。