Created
December 21, 2018 15:12
-
-
Save luiswolff/06d3d421c2a5319dc70965268151fcef to your computer and use it in GitHub Desktop.
Example on how to sign file content using a randomly generated private Key. The Code takes a file as input and generates a signature and a public key, that can be used to verify, that the signature was create by the generated private 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.io.IOException; | |
import java.nio.file.Files; | |
import java.nio.file.Path; | |
import java.nio.file.Paths; | |
import java.security.KeyPair; | |
import java.security.KeyPairGenerator; | |
import java.security.PrivateKey; | |
import java.security.SecureRandom; | |
import java.security.Signature; | |
public class MessageSignGenerator { | |
public static void main(String[] args) { | |
if (args.length != 1) { | |
System.out.println("Usage: MessageSignGenerator nameOfFileToSign"); | |
} else try { | |
createSignature(args[0]); | |
System.out.println("Signed file " + args[0]); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
private static void createSignature(String file) throws Exception, IOException { | |
KeyPair keyPair = createKeyPair(); | |
byte[] sign = sign(Paths.get(file), keyPair.getPrivate()); | |
write(Paths.get(file + ".sig"), sign); | |
write(Paths.get(file + ".suepk"), keyPair.getPublic().getEncoded()); | |
} | |
private static KeyPair createKeyPair() throws Exception { | |
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA"); | |
SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); | |
keyGen.initialize(1024, random); | |
return keyGen.generateKeyPair(); | |
} | |
private static byte[] sign(Path path, PrivateKey privateKey) throws Exception { | |
Signature dsa = Signature.getInstance("SHA1withDSA"); | |
dsa.initSign(privateKey); | |
dsa.update(Files.readAllBytes(path)); | |
return dsa.sign(); | |
} | |
private static void write(Path path, byte[] content) throws IOException { | |
Files.write(path, content); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment