Class SignatureUtil

java.lang.Object
ca.corbett.extras.crypt.SignatureUtil

public class SignatureUtil extends Object
This utility class provides convenient wrappers for creating public/private key pairs, using a private key to sign a file, and using a public key to verify a file signature.

How do I sign a file? - You generate a key pair, save the public/private keys, and then use the private key to sign the file.

 KeyPair keyPair = SignatureUtil.generateKeyPair();
 SignatureUtil.saveKeyPair(keyPair, privateKeyFile, publicKeyFile); // keep the private key safe!

 // Generate a signature and save it to "signatureFile":
 SignatureUtil.signFile(dataFile, keyPair.getPrivate(), signatureFile);
 

You can bundle signatureFile and your publicKeyFile together with the dataFile that you wish to transmit. The receiver can use the public key to verify the signature and confirm that dataFile has not been modified since it was signed:

 PublicKey publicKey = SignatureUtil.loadPublicKey(publicKeyFile);
 boolean isValid = SignatureUtil.verifyFile(dataFile, signatureFile, publicKey);
 if (! isValid) {
     throw new Exception("The signature is wrong! The file has been modified!");
 }
 

Note: there is a generateKeyPair method in this class as a convenience. It is perfectly compatible with the following manual generation approach:

 # Generate key pair
 ssh-keygen -t rsa -b 2048 -m PEM -f mykey -N ""

 # Convert private key to PKCS#8
 openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in mykey -out mykey.pkcs8

 # Convert public key to X.509 PEM
 ssh-keygen -f mykey -e -m PEM | openssl rsa -pubin -RSAPublicKey_in -pubout -out mykey_pub.pem
 

Java is very particular about key formats, and it doesn't seem to like the usual openssh format. So, we use PKCS#8 in PEM format (this is what you get out of the box with the java.security classes).

Since:
swing-extras 2.5
Author:
scorbo2 with help from claude.ai