Skip to content

Instantly share code, notes, and snippets.

@luiswolff
Created December 21, 2018 15:12
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/06d3d421c2a5319dc70965268151fcef to your computer and use it in GitHub Desktop.
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.
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