Skip to content

Instantly share code, notes, and snippets.

@luiswolff
Created December 21, 2018 15:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luiswolff/5902800cf44b70a7365dfd69c31bdbeb to your computer and use it in GitHub Desktop.
Save luiswolff/5902800cf44b70a7365dfd69c31bdbeb to your computer and use it in GitHub Desktop.
Example on how to verify a data file using a provided signature and public key.
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;
public class MessageSignVerifier {
public static void main(String[] args) {
if (args.length != 3) {
System.out.println("Usage: MessageSignVerifier dataFile signatureFile publicKeyFile");
} else try {
verify(args[0], args[1], args[2]);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void verify(String dataFile, String signatureFile, String publicKeyFile) throws Exception {
PublicKey pubKey = readKey(Paths.get(publicKeyFile));
byte[] sigToVerify = Files.readAllBytes(Paths.get(signatureFile));
byte[] data = Files.readAllBytes(Paths.get(dataFile));
checkSignature(pubKey, sigToVerify, data);
}
private static PublicKey readKey(Path path) throws Exception {
byte[] encodedKey = Files.readAllBytes(path);
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encodedKey);
KeyFactory keyFactory = KeyFactory.getInstance("DSA");
return keyFactory.generatePublic(pubKeySpec);
}
private static void checkSignature(PublicKey pubKey, byte[] sigToVerify, byte[] data) throws Exception {
Signature signature = Signature.getInstance("SHA1withDSA");
signature.initVerify(pubKey);
signature.update(data);
boolean valid = signature.verify(sigToVerify);
if (valid) {
System.out.println("Signature is korrect");
} else {
System.err.println("Could not verify signature!!!");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment