Java Requires Chilkat v10.1.2+
Chilkat2 Java
Create PKCS7 Signed File (.p7m)
See more Encryption Examples
Demonstrates how to sign a file to create a .p7m that contains both the file contents and the signature.Chilkat Java Downloads
import com.chilkatsoft.chilkat2.Cert;
import com.chilkatsoft.chilkat2.CertStore;
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Crypt2;
import com.chilkatsoft.chilkat2.JsonObject;
public class ChilkatExample {
public static void main(String[] args) {
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
Crypt2 crypt = new Crypt2();
CertStore certStore = new CertStore();
// Load a PFX file into a certificate store object.
try {
certStore.loadPfxFile("myPfx.pfx", "pfxPassword");
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// Get the certificate by subject common name.
// This should be the cert within the PFX that also
// has a private key (also stored within the PFX).
JsonObject jsonCN = new JsonObject();
jsonCN.updateString("CN", "myCert");
Cert cert = new Cert();
try {
certStore.findCert(jsonCN, cert);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// Tell the crypt object to use the certificate for signing:
crypt.setSigningCert(cert);
// Sign a file, producing a .p7m as output.
// The input file is unchanged, the test.p7m contains the
// contents of the input file and the signature.
String inFile = "test.txt";
String outFile = "testp7m";
try {
crypt.createP7M(inFile, outFile);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
System.out.println("Success!");
}
}