I did do initialization for signing by calling the method initSign(Private key) but I still get exception. Here is my code.
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);
}
Here is my exception:
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)
Anybody help? Thanks!
Don't use the same variable 'sign' for both signing and verifying. sign.initVerify overrides sign.initSign. Rather use one variable for signing and another one for verifying.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.