In this example we will learn how to verify the digital signature of the previously signed data. To sign the data you can see the previous example on this post How to create a digital signature and sign data?.
Here the code snippet:
package org.kodejava.example.security;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;
public class VerifyDigitalSignature {
public static void main(String[] args) {
try {
byte[] publicKeyEncoded = Files.readAllBytes(Paths.get("publickey"));
byte[] digitalSignature = Files.readAllBytes(Paths.get("signature"));
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyEncoded);
KeyFactory keyFactory = KeyFactory.getInstance("DSA", "SUN");
PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
Signature signature = Signature.getInstance("SHA1withDSA", "SUN");
signature.initVerify(publicKey);
byte[] bytes = Files.readAllBytes(Paths.get("README"));
signature.update(bytes);
boolean verified = signature.verify(digitalSignature);
if (verified) {
System.out.println("Data verified.");
} else {
System.out.println("Cannot verify data.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Latest posts by Wayan (see all)
- How do I create a generic class in Java? - January 1, 2021
- How do I convert java.util.TimeZone to java.time.ZoneId? - April 25, 2020
- How do I get a list of all TimeZones Ids using Java 8? - April 25, 2020
The above code couldn’t run in my system.
Gave
java.security.spec.InvalidKeySpecException: Inappropriate key specification: IOException: DerInputStream.getLength(): lengthTag=111, too big.
At line >> PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
Hi Subuhi, you might also want to check the following example How to create a digital signature and sign data?