Created
December 21, 2018 15:14
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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