The clear signature OpenPGP message format is designed to sign text messages. The original message is kept as is and an additional signature is appended. This way the recipient can still read the original message without special software.
Clear signed messages are verified just like ordinary signed data.
The examples below demonstrate how to achieve this with DidiSoft OpenPGP Library for Java.
1) Clearsign string message with private key located in file
This example shows how to clear sign a text message. The signature algorithm is specified explicitly in contrast to the standard sign method.
import com.didisoft.pgp.HashAlgorithm;
import com.didisoft.pgp.PGPLib;
public class ClearSignString {
public static void main(String[] args) throws Exception{
// create an instance of the library
PGPLib pgp = new PGPLib();
String message = "The quick brown fox jumps.";
// clear sign
String clearSignedMessage =
pgp.clearSignString(message,
"private.asc", "private key pass",
HashAlgorithm.SHA256);
}
}
2) Clearsign file with private key located in file
This example demonstrates how to clear text sign a file. The result file will contain the original file contents intact and an additional signature.
import com.didisoft.pgp.HashAlgorithm;
import com.didisoft.pgp.PGPLib;
public class ClearSignFile {
public static void main(String[] args) throws Exception{
// create an instance of the library
PGPLib pgp = new PGPLib();
// clear sign
pgp.clearSignFile("INPUT.txt",
"private.asc", "private key pass",
HashAlgorithm.SHA256,
"OUTPUT.sig.txt");
}
}
3) Exception Handling
The clear text sign methods exposed by the library throw java.io.IOException and com.didisoft.pgp.PGPException by contract.
There are additionally a few sub classes of PGPException that we can catch before PGPException itself, in order to identify more clearly the exact error cause. Take a look at the example below for details:
import java.io.IOException;
import com.didisoft.pgp.*;
import com.didisoft.pgp.exceptions.*;
public class ExceptionHandlingDemo {
public static void main(String[] a) {
PGPLib pgp = new PGPLib();
try {
pgp.decrypt...
} catch (IOException e) {
// I/O error reading input or writing output
} catch (KeyIsExpiredException e) {
// the passed private key file is expired
} catch (KeyIsRevokedException e) {
// the passed private key file is revoked
} catch (NoPrivateKeyFoundException e) {
// the passed private key source does not contain a private key
} catch (WrongPasswordException e) {
// the password for the provided private key is wrong
} catch (PGPException e) {
// general error during signing, not among the above ones
}
}
}