我确实通过调用initSign(私钥)方法进行了签名初始化,但我仍然遇到异常。这是我的代码。
public static boolean verify() throws SignatureException{
File signed = new File("/Users/main/Documents/workspace/test/src/lorem_ipsum.txt");
byte[] b = new byte[(int) signed.length()];
try {
FileInputStream fileInputStream = new FileInputStream(signed);
System.out.println("Before read b is: "+ b);
fileInputStream.read(b);
for (int i = 0; i < b.length; i++) {
//System.out.print((char)b[i]);
}
} catch (FileNotFoundException e) {
//System.out.println("File Not Found.");
e.printStackTrace();
}
catch (IOException e1)
{
//System.out.println("Error Reading The File.");
e1.printStackTrace();
}
KeyPairGenerator kpg = null;
try {
kpg = KeyPairGenerator.getInstance("RSA");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
kpg.initialize(2048);
KeyPair kp = kpg.genKeyPair();
PublicKey publicKey = (PublicKey) kp.getPublic();
PrivateKey privateKey = (PrivateKey) kp.getPrivate();
Signature sign = null;
try {
sign = Signature.getInstance("SHA1withRSA");
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
sign.initSign((PrivateKey) privateKey);
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
sign.initVerify((PublicKey)publicKey);
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
sign.update(b);
} catch (SignatureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] signed2 = sign.sign();
return sign.verify(signed2);
}
这是我的例外:
Exception in thread "main" java.security.SignatureException: object not initialized for signing
at java.security.Signature.sign(Signature.java:524)
at test.verify(test.java:114)
at test.main(test.java:215)
有人帮忙吗?谢谢!
答案 0 :(得分:3)
不要对签名和验证使用相同的变量'sign'。 sign.initVerify覆盖sign.initSign。而是使用一个变量进行签名,另一个变量用于验证。