Certificates in Java: keytool, Certificate Chains and Signing JAR Files
Solving the authentication problem with X.509 certificates: what a certificate contains, certificate authorities and chains of trust, keytool and PKCS #12 key stores, PKIX path validation in code, and signing and verifying JAR files with jarsigner and the JarSigner API.
kvi5hnuCode Sprout team member12 min readOn this page
Article 84 ended with a warning: a valid signature proves that data was signed with a particular private key, but not whose key it is. Anyone can generate a key pair, sign a program, and send you the public key with a note saying "this is from Big Software Inc." Deciding who really owns a public key is the authentication problem. This article covers the standard solution, X.509 certificates, and the JDK tools and APIs that work with them: keytool, key stores, certificate path validation and JAR signing.
The authentication problem
If you know Alice personally, you can check Alice's key yourself: Alice reads the key's fingerprint to you over the phone, and you compare it with the file you received. That does not scale to strangers. The practical answer is a trusted intermediary. Someone you already trust checks the stranger's identity and then signs a statement saying "this public key belongs to this person". If you can verify that signature, you can believe the statement, as far as you trust the signer's diligence.
That signed statement is a certificate. The signer is a certificate authority (CA). And since CAs can certify other CAs, certificates form chains that end at a root certificate, which is signed by itself and trusted because it was installed deliberately, for example by the operating system, the browser, or the JDK.

What an X.509 certificate contains
Nearly all certificates use the X.509 version 3 format. The important fields:
| Field | Meaning |
|---|---|
| Subject | Who the key belongs to, as an X.500 distinguished name such as CN=Alice Lee, OU=Engineering, O=ACME Software, C=US (common name, organizational unit, organization, locality L, state ST, country C). TLS certificates put host names in the subject alternative name extension instead. |
| Subject public key | The key being certified, with its algorithm. |
| Issuer | The distinguished name of the CA that signed it. |
| Serial number | Unique per issuer; used in revocation lists. |
| Validity | notBefore and notAfter. Outside this window the certificate is invalid. |
| Extensions | Basic constraints (is this a CA?), key usage (digitalSignature, keyCertSign, ...), extended key usage (code signing, TLS server, ...), key identifiers, CRL and OCSP locations. |
| Signature | The issuer's signature over all of the above, and its algorithm. |
A certificate is public; it contains no private key. Its fingerprint (the SHA-256 digest of its encoding) is a convenient short identifier for comparing certificates by eye.
In Java, a certificate is a java.security.cert.X509Certificate, created by a CertificateFactory from DER or PEM bytes. It has getters for all fields, and verify(issuerPublicKey) checks its signature.
Certificate authorities in practice
What a CA certifies depends on its policies. For TLS server certificates there are three levels: domain validated (the requester controls the domain, checked automatically), organization validated, and extended validation (legal documents checked). A code-signing certificate attests to an organization or individual, and since 2023 industry rules require its private key to live in a hardware token or cloud HSM. When you trust a signature, be clear about what was actually verified.
Certificate lifetimes are getting shorter. Under a 2025 CA/Browser Forum decision, the maximum validity of public TLS certificates falls from 398 days to 200 days in March 2026, 100 days in March 2027 and 47 days in March 2029. Automated renewal (ACME, as used by Let's Encrypt) is becoming a necessity.
Certificates can also be revoked before they expire, for example when a private key is stolen. Validators learn this from certificate revocation lists (CRLs) or the online status protocol OCSP; Java's PKIX validator can check both.
keytool and key stores
A key store is a file holding private keys (each with its certificate chain) and trusted certificates, each under an alias. Since Java 9 the default format is PKCS #12 (.p12/.pfx), an interoperable standard; the old Java-only JKS format is legacy. The JDK's own trust store, $JAVA_HOME/lib/security/cacerts, is a PKCS #12 file with the root certificates of well-known CAs (its traditional password is changeit; reading it needs no password).
keytool manages key stores from the command line. To reproduce the scenario in the diagram:
# The company CA creates its root key pair and exports its self-signed certificate
keytool -genkeypair -keyalg Ed25519 -alias acmeroot -keystore root.p12 \
-dname "CN=ACME Root CA, O=ACME Software, C=US" -ext bc:c -validity 7300
keytool -exportcert -rfc -alias acmeroot -keystore root.p12 -file root.cer
# Alice creates a key pair and a certificate signing request (CSR)
keytool -genkeypair -keyalg Ed25519 -alias alice -keystore alice.p12 \
-dname "CN=Alice Lee, OU=Engineering, O=ACME Software, C=US"
keytool -certreq -alias alice -keystore alice.p12 -file alice.req
# The CA checks Alice's identity and issues Alice's certificate
keytool -gencert -alias acmeroot -keystore root.p12 -infile alice.req -outfile alice.cer -rfc \
-validity 1095 -ext KeyUsage=digitalSignature -ext ExtendedKeyUsage=codeSigning
# Alice installs the root (to complete the chain) and then the reply from the CA
keytool -importcert -alias acmeroot -keystore alice.p12 -file root.cer
keytool -importcert -alias alice -keystore alice.p12 -file alice.cer
Other common commands: -list -v (show entries), -printcert -file x.cer (show a certificate file, including fingerprints), -printcert -sslserver host:443 (show a server's chain), -importkeystore (convert between formats), -delete, -changealias, and -cacerts as a shortcut for the JDK trust store. -keyalg is mandatory; RSA, EC, Ed25519, Ed448 and, since Java 24, ML-DSA (with -groupname ML-DSA-65) are all accepted. Without -validity, a new certificate is valid for 90 days. -rfc writes the Base64 PEM form instead of binary DER.
Graphical tools exist too; KeyStore Explorer is a popular free one.
Key stores and validation in code
The KeyStore class reads and writes the same files:
KeyStore ks = KeyStore.getInstance(new File("alice.p12"), password); // detects the type
PrivateKey key = (PrivateKey) ks.getKey("alice", password);
Certificate[] chain = ks.getCertificateChain("alice");
To decide whether a certificate is trustworthy, do not just call verify on each link yourself. The PKIX CertPathValidator implements the full rules: signatures, validity dates, basic constraints, key usage, name chaining and, when enabled, revocation:
var params = new PKIXParameters(Set.of(new TrustAnchor(rootCert, null))); // or new PKIXParameters(trustStore)
params.setRevocationEnabled(true);
CertPath path = CertificateFactory.getInstance("X.509").generateCertPath(List.of(leafCert));
CertPathValidator.getInstance("PKIX").validate(path, params); // throws CertPathValidatorException
The exception's getReason() gives a machine-readable cause such as EXPIRED, NO_TRUST_ANCHOR or REVOKED. TLS connections (HttpClient, SSLSocket) run this validation for you against cacerts or a trust store you configure.
Code signing and JAR files
The JAR format has built-in support for signatures. jarsigner signs a JAR with a key from a key store and verifies signed JARs:
jarsigner -keystore alice.p12 document.jar alice
jarsigner -verify -verbose -certs -keystore bob.p12 document.jar
Signing adds three files to META-INF: the manifest gets a digest of every entry; ALICE.SF (the signature file) holds digests of the manifest and its sections; and a signature block (ALICE.RSA, .EC or .DSA, also used for EdDSA as .EC) holds the signature over the .SF file plus the certificate chain. Changing any entry breaks a digest, and changing the digests breaks the signature.
Add a timestamp from a timestamping authority with -tsa url. Without one, the signature stops being verifiable as valid once the signer's certificate expires; with one, it remains valid because it is provably older than the expiry.
The same operations are available as APIs:
jdk.security.jarsigner.JarSigner(modulejdk.jartool, Java 9) signs a JAR in code.java.util.jar.JarFileverifies when opened withverify = true(the default). Verification happens as you read: only after you have read an entry completely doesJarEntry.getCodeSigners()report its signers. A tampered entry throwsSecurityExceptionduring reading. Note thatJarFileonly proves the entries match the signature and the certificate inside the JAR; it does not check that the certificate is trusted, unexpired or unrevoked. To decide whether to trust the signer, validatesigners[0].getSignerCertPath()withCertPathValidatoragainst your trust anchors, as shown above (or usejarsigner -verify -strict).
What does a signed JAR buy you today? The original purpose, granting extra permissions to signed applets and Web Start applications, is gone with the applet plugin and the Security Manager. What remains is integrity and origin: you can confirm that a library or plugin was built by a party whose certificate you trust, and update systems use exactly that check. Two current rules to know: the JDK treats JARs signed with SHA-1 as unsigned (since Java 18), and jlink refuses signed modular JARs unless you pass --ignore-signing-information, because the signature would no longer match after linking.
The program
The demo embeds three certificates that were created with the keytool commands above (with fixed start dates): the ACME root, Alice's code-signing certificate, and a self-signed certificate in which Mallory uses Alice's name. It also embeds Alice's private key (a demo key, never do this with a real one). The program:
- prints the fields of Alice's certificate;
- checks certificate signatures by hand with
verify; - runs PKIX validation with the root as the only trust anchor, at two fixed dates, so the "expired" case is repeatable;
- builds a PKCS #12 key store in memory, saves and reloads it, and peeks at the JDK's
cacerts; - creates a JAR, signs it with
JarSigner, verifies it withJarFile, then changes one byte of the document inside the signed JAR and reads it again.
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.security.*;
import java.security.cert.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.time.*;
import java.util.*;
import java.util.jar.*;
import java.util.zip.*;
import jdk.security.jarsigner.JarSigner;
public class Solution {
// Made with keytool: a root CA, a code-signing certificate for Alice issued by it,
// and a self-signed certificate in which "Mallory" claims to be Alice. All Ed25519.
static final String ROOT_PEM = """
-----BEGIN CERTIFICATE-----
MIIBbTCCAR+gAwIBAgIIWeCJWlU/OcQwBQYDK2VwMDwxCzAJBgNVBAYTAlVTMRYw
FAYDVQQKEw1BQ01FIFNvZnR3YXJlMRUwEwYDVQQDEwxBQ01FIFJvb3QgQ0EwHhcN
MjYwMTAxMDk1MTAyWhcNNDUxMjI3MDk1MTAyWjA8MQswCQYDVQQGEwJVUzEWMBQG
A1UEChMNQUNNRSBTb2Z0d2FyZTEVMBMGA1UEAxMMQUNNRSBSb290IENBMCowBQYD
K2VwAyEAKTODE2NsIJre6+u3xj+IO4AOWBz84gnEC+dqpocT6U6jPzA9MB0GA1Ud
DgQWBBTePK26VcH4Zw1/26bYtHcU7rZahTALBgNVHQ8EBAMCAQYwDwYDVR0TAQH/
BAUwAwEB/zAFBgMrZXADQQAgAsYMTpzKTGDQY2bJVS6efg16ZGyq5yax/45FR0Qg
Q0nnbGX/GdIlxWtzsxDlqeLp+tXK/xvvny8DEzOgFbUK
-----END CERTIFICATE-----
""";
static final String ALICE_PEM = """
-----BEGIN CERTIFICATE-----
MIIBpjCCAVigAwIBAgIJAIkj6lI6ixZBMAUGAytlcDA8MQswCQYDVQQGEwJVUzEW
MBQGA1UEChMNQUNNRSBTb2Z0d2FyZTEVMBMGA1UEAxMMQUNNRSBSb290IENBMB4X
DTI2MDMwMTA5NTEwMloXDTI5MDIyODA5NTEwMlowTzELMAkGA1UEBhMCVVMxFjAU
BgNVBAoTDUFDTUUgU29mdHdhcmUxFDASBgNVBAsTC0VuZ2luZWVyaW5nMRIwEAYD
VQQDEwlBbGljZSBMZWUwKjAFBgMrZXADIQDZLq7kDtoVk32CSxhahIccsDut2hwt
57t3Upj9H3wZkaNkMGIwHQYDVR0OBBYEFFa6ppNApCg58BPt3v6e0vrBRikOMAsG
A1UdDwQEAwIHgDAfBgNVHSMEGDAWgBTePK26VcH4Zw1/26bYtHcU7rZahTATBgNV
HSUEDDAKBggrBgEFBQcDAzAFBgMrZXADQQACQR2bUanOa+0/m4LdkkbAXYGpWxLG
utYDl1GcqwheRFBvxNtiyzCzNeELrQx5L4PC1ygP4hboO95ckJwOBnsA
-----END CERTIFICATE-----
""";
static final String MALLORY_PEM = """
-----BEGIN CERTIFICATE-----
MIIBdjCCASigAwIBAgIJAOPNhyaeEUQZMAUGAytlcDBPMQswCQYDVQQGEwJVUzEW
MBQGA1UEChMNQUNNRSBTb2Z0d2FyZTEUMBIGA1UECxMLRW5naW5lZXJpbmcxEjAQ
BgNVBAMTCUFsaWNlIExlZTAeFw0yNjAxMDEwOTUxMDNaFw0zNTEyMzAwOTUxMDNa
ME8xCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1BQ01FIFNvZnR3YXJlMRQwEgYDVQQL
EwtFbmdpbmVlcmluZzESMBAGA1UEAxMJQWxpY2UgTGVlMCowBQYDK2VwAyEAdeIW
iO5gdf6uyI78puXga2hoT9OINncaY5qh7wg+FaCjITAfMB0GA1UdDgQWBBTrE0hV
S9MewIjREOflL+EKPbA29jAFBgMrZXADQQB9c9xrdMJ79MIVHvQVFsqsYV1+ti58
6ymyLVU4gn46QcnOnxHnDY8Dg6hHO60Lj4EX1o2LzM+3rOHnb2CLTEwN
-----END CERTIFICATE-----
""";
// Alice's private key (PKCS #8, Base64). Published here only because this is a demo key.
static final String ALICE_KEY = "MC4CAQAwBQYDK2VwBCIEIFD1yWnhTp6SuijB588TEVQ8obSzQrm2u+uDrCN3m77d";
static X509Certificate parse(String pem) throws CertificateException {
var cf = CertificateFactory.getInstance("X.509");
return (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(pem.getBytes(StandardCharsets.US_ASCII)));
}
static String fingerprint(X509Certificate c) throws Exception {
byte[] d = MessageDigest.getInstance("SHA-256").digest(c.getEncoded());
return HexFormat.ofDelimiter(":").withUpperCase().formatHex(d, 0, 8) + ":...";
}
static String validate(X509Certificate cert, X509Certificate trusted, Instant when) throws Exception {
var params = new PKIXParameters(Set.of(new TrustAnchor(trusted, null)));
params.setRevocationEnabled(false); // no CRL/OCSP servers in this demo
params.setDate(Date.from(when));
CertPath path = CertificateFactory.getInstance("X.509").generateCertPath(List.of(cert));
try {
var result = (PKIXCertPathValidatorResult) CertPathValidator.getInstance("PKIX").validate(path, params);
return "VALID, anchored at " + result.getTrustAnchor().getTrustedCert().getSubjectX500Principal().getName();
} catch (CertPathValidatorException e) {
return "INVALID (" + e.getReason() + "): " + e.getMessage();
}
}
public static void main(String[] args) throws Exception {
X509Certificate root = parse(ROOT_PEM), alice = parse(ALICE_PEM), mallory = parse(MALLORY_PEM);
System.out.println("== What a certificate contains ==");
System.out.println("version: " + alice.getVersion());
System.out.println("subject: " + alice.getSubjectX500Principal().getName());
System.out.println("issuer: " + alice.getIssuerX500Principal().getName());
System.out.println("serial: " + alice.getSerialNumber().toString(16));
System.out.println("valid: " + alice.getNotBefore().toInstant() + " to " + alice.getNotAfter().toInstant());
System.out.println("public key: " + alice.getPublicKey().getAlgorithm());
System.out.println("signed with: " + alice.getSigAlgName() + " by the issuer");
System.out.println("key usage: digitalSignature=" + alice.getKeyUsage()[0] + ", keyCertSign=" + alice.getKeyUsage()[5]);
System.out.println("extended usage: " + alice.getExtendedKeyUsage() + " (1.3.6.1.5.5.7.3.3 = code signing)");
System.out.println("is a CA: " + (alice.getBasicConstraints() >= 0) + " (root: " + (root.getBasicConstraints() >= 0) + ")");
System.out.println("SHA-256 fingerprint: " + fingerprint(alice));
System.out.println("\n== Checking signatures on certificates by hand ==");
root.verify(root.getPublicKey());
System.out.println("root is self-signed: ok");
alice.verify(root.getPublicKey());
System.out.println("alice signed by the root: ok");
try {
mallory.verify(root.getPublicKey());
} catch (SignatureException e) {
System.out.println("mallory signed by the root: no (" + e.getClass().getSimpleName() + ")");
}
System.out.println("same subject name? " + mallory.getSubjectX500Principal().equals(alice.getSubjectX500Principal())
+ ", same key? " + mallory.getPublicKey().equals(alice.getPublicKey()));
System.out.println("\n== PKIX path validation with the root as trust anchor ==");
Instant mid2026 = Instant.parse("2026-07-01T00:00:00Z");
System.out.println("alice @2026-07-01: " + validate(alice, root, mid2026));
System.out.println("mallory @2026-07-01: " + validate(mallory, root, mid2026));
System.out.println("alice @2030-01-01: " + validate(alice, root, Instant.parse("2030-01-01T00:00:00Z")));
System.out.println("\n== A PKCS #12 key store ==");
PrivateKey aliceKey = KeyFactory.getInstance("Ed25519")
.generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(ALICE_KEY)));
char[] password = "secret".toCharArray();
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(null, null); // a new, empty store
ks.setCertificateEntry("acmeroot", root);
ks.setKeyEntry("alice", aliceKey, password, new java.security.cert.Certificate[] {alice, root});
var bytes = new ByteArrayOutputStream();
ks.store(bytes, password);
KeyStore loaded = KeyStore.getInstance("PKCS12");
loaded.load(new ByteArrayInputStream(bytes.toByteArray()), password);
for (String alias : new TreeSet<>(Collections.list(loaded.aliases())))
System.out.println(alias + ": " + (loaded.isKeyEntry(alias) ? "private key + chain of "
+ loaded.getCertificateChain(alias).length : "trusted certificate"));
System.out.println("certificate alias for Alice's cert: " + loaded.getCertificateAlias(alice));
Path cacerts = Path.of(System.getProperty("java.home"), "lib", "security", "cacerts");
KeyStore jdkRoots = KeyStore.getInstance(cacerts.toFile(), (char[]) null);
System.out.println("JDK cacerts holds more than 50 trusted roots: " + (jdkRoots.size() > 50));
System.out.println("\n== Signing a JAR file (the API behind jarsigner) ==");
Path dir = Files.createTempDirectory("signing");
Path unsigned = dir.resolve("document.jar"), signed = dir.resolve("document-signed.jar");
byte[] text = "Pay Bob 100 euros on 2026-07-01.\n".getBytes(StandardCharsets.UTF_8);
try (var out = new JarOutputStream(Files.newOutputStream(unsigned))) {
var e = new JarEntry("document.txt");
e.setMethod(ZipEntry.STORED); // uncompressed, so we can tamper below
var crc = new CRC32();
crc.update(text);
e.setSize(text.length);
e.setCrc(crc.getValue());
out.putNextEntry(e);
out.write(text);
}
CertPath chain = CertificateFactory.getInstance("X.509").generateCertPath(List.of(alice, root));
JarSigner signer = new JarSigner.Builder(aliceKey, chain).digestAlgorithm("SHA-256").signerName("ALICE").build();
try (var zip = new ZipFile(unsigned.toFile()); var out = Files.newOutputStream(signed)) {
signer.sign(zip, out);
}
try (var jar = new JarFile(signed.toFile())) {
System.out.println("entries: " + jar.stream().map(JarEntry::getName).toList());
}
System.out.println("document.txt: " + readSigned(signed));
byte[] raw = Files.readAllBytes(signed);
int at = indexOf(raw, "100 euros".getBytes(StandardCharsets.UTF_8));
raw[at] = '9'; // 100 -> 900 euros
Path tampered = dir.resolve("tampered.jar");
Files.write(tampered, raw);
System.out.println("tampered: " + readSigned(tampered));
for (Path p : List.of(unsigned, signed, tampered)) Files.delete(p);
Files.delete(dir);
}
/** Reads document.txt from a JAR with verification on and reports who signed it. */
static String readSigned(Path jarPath) throws IOException {
try (var jar = new JarFile(jarPath.toFile(), true)) {
JarEntry e = jar.getJarEntry("document.txt");
String content;
try (InputStream in = jar.getInputStream(e)) {
content = new String(in.readAllBytes(), StandardCharsets.UTF_8).strip(); // must read fully first
}
CodeSigner[] signers = e.getCodeSigners();
if (signers == null) return "\"" + content + "\" (NOT signed)";
var cert = (X509Certificate) signers[0].getSignerCertPath().getCertificates().get(0);
return "\"" + content + "\" signed by " + cert.getSubjectX500Principal().getName()
+ ", timestamp " + signers[0].getTimestamp();
} catch (SecurityException e) {
return "SecurityException: " + e.getMessage();
}
}
static int indexOf(byte[] hay, byte[] needle) {
outer:
for (int i = 0; i <= hay.length - needle.length; i++) {
for (int j = 0; j < needle.length; j++) if (hay[i + j] != needle[j]) continue outer;
return i;
}
return -1;
}
}
== What a certificate contains ==
version: 3
subject: CN=Alice Lee,OU=Engineering,O=ACME Software,C=US
issuer: CN=ACME Root CA,O=ACME Software,C=US
serial: 8923ea523a8b1641
valid: 2026-03-01T09:51:02Z to 2029-02-28T09:51:02Z
public key: EdDSA
signed with: Ed25519 by the issuer
key usage: digitalSignature=true, keyCertSign=false
extended usage: [1.3.6.1.5.5.7.3.3] (1.3.6.1.5.5.7.3.3 = code signing)
is a CA: false (root: true)
SHA-256 fingerprint: AE:61:C5:5A:A0:32:00:16:...
== Checking signatures on certificates by hand ==
root is self-signed: ok
alice signed by the root: ok
mallory signed by the root: no (SignatureException)
same subject name? true, same key? false
== PKIX path validation with the root as trust anchor ==
alice @2026-07-01: VALID, anchored at CN=ACME Root CA,O=ACME Software,C=US
mallory @2026-07-01: INVALID (NO_TRUST_ANCHOR): Path does not chain with any of the trust anchors
alice @2030-01-01: INVALID (EXPIRED): validity check failed
== A PKCS #12 key store ==
acmeroot: trusted certificate
alice: private key + chain of 2
certificate alias for Alice's cert: alice
JDK cacerts holds more than 50 trusted roots: true
== Signing a JAR file (the API behind jarsigner) ==
entries: [META-INF/MANIFEST.MF, META-INF/ALICE.SF, META-INF/ALICE.EC, document.txt]
document.txt: "Pay Bob 100 euros on 2026-07-01." signed by CN=Alice Lee,OU=Engineering,O=ACME Software,C=US, timestamp null
tampered: SecurityException: SHA-256 digest error for document.txt
Points to notice:
- Mallory's certificate has exactly the same subject name as Alice's, so names alone prove nothing. Only the chain to a trusted anchor distinguishes them.
- The serial number and the first fingerprint bytes match what
keytool -printcert -file alice.cerdisplays. timestamp nullmeans the JAR was signed without a timestamping authority.- The tampered JAR is still a well-formed ZIP file; the digest recorded in the signed manifest exposes the change.
Common questions
How do I trust a self-signed or company-internal certificate in Java?
Import it into a trust store: keytool -importcert -alias corp -file corp-ca.pem -keystore truststore.p12, then run with -Djavax.net.ssl.trustStore=truststore.p12 (and the password), or load it into an SSLContext in code. Prefer importing the company's CA certificate, not each server's certificate.
Should I add certificates to the JDK's cacerts?
It works, but JDK updates replace cacerts, and every application on that JDK trusts the addition. A separate trust store per application, or the operating system's store (-Djavax.net.ssl.trustStoreType=KeychainStore-ROOT for the macOS system roots since Java 23, KeychainStore for the user's login keychain, Windows-ROOT on Windows), is easier to maintain.
How do I convert between PEM, DER, JKS and PKCS #12?
keytool -importkeystore converts JKS to PKCS #12. keytool -exportcert -rfc writes PEM, and without -rfc writes DER. For private keys in PEM files, OpenSSL is the usual tool (openssl pkcs12 -export combines a key and certificate into a .p12 that Java reads).
How do I check when a server's certificate expires?
keytool -printcert -sslserver host:443 prints the chain with validity dates. In code, X509Certificate.getNotAfter() on the certificates from SSLSession.getPeerCertificates().
Do I need to sign my JARs? Only if consumers verify signatures, for example for a plugin system or certain enterprise policies. Maven Central requires PGP signatures on uploaded artifacts, which are separate files, not JAR signatures.
API reference
| Class / method | Purpose |
|---|---|
CertificateFactory.getInstance("X.509").generateCertificate(in) | Parse a DER or PEM certificate. |
X509Certificate.getSubjectX500Principal(), getIssuerX500Principal(), getSerialNumber(), getNotBefore(), getNotAfter() | Identity and validity fields. |
getKeyUsage(), getExtendedKeyUsage(), getBasicConstraints(), getSubjectAlternativeNames() | Extensions. |
getPublicKey(), getSigAlgName(), getEncoded(), verify(key), checkValidity(date) | Key, signature and checks. |
KeyStore.getInstance("PKCS12") / getInstance(file, password) | Create or open a key store. |
load, store, aliases, getKey, getCertificate, getCertificateChain, setKeyEntry, setCertificateEntry, isKeyEntry | Key store operations. |
CertificateFactory.generateCertPath(list) | Build a path to validate. |
PKIXParameters(anchors or keystore), setRevocationEnabled, setDate | Validation settings. |
CertPathValidator.getInstance("PKIX").validate(path, params) | Validate; CertPathValidatorException.getReason() on failure. |
jdk.security.jarsigner.JarSigner.Builder(key, certPath).build().sign(zip, out) | Sign a JAR in code. |
JarFile(file, true), JarEntry.getCodeSigners(), CodeSigner.getSignerCertPath(), getTimestamp() | Verify a signed JAR. |
keytool, jarsigner | Command-line tools for the same tasks. |
Summary
- A certificate is a CA's signed statement binding a subject name to a public key, with validity dates and usage extensions. It solves the authentication problem as far as you trust the CA.
- Certificates form chains that end at a self-signed root in a trust store such as
cacerts. Validate with PKIXCertPathValidator, not by checking signatures alone. keytoolcreates key pairs, CSRs and certificates and manages PKCS #12 key stores;KeyStoredoes the same in code. Import a certificate as trusted only after checking its fingerprint.- Signed JARs carry digests in the manifest, a
.SFfile and a signature block. Verify withjarsigner -verifyor by reading entries fully from a verifyingJarFile. Timestamp signatures with-tsa. - Signed code no longer receives special permissions; signing provides integrity and origin. SHA-1 signed JARs count as unsigned.
Practice Questions
1. A certificate says CN=Big Software Inc. and its signature checks out with its own public key. Should you trust code signed with it?
No. A certificate that verifies with its own key is self-signed, and anyone can create one with any name in seconds, as Mallory's certificate in the demo shows. Trust requires a chain from the certificate to a trust anchor you installed deliberately, or a fingerprint you confirmed through an independent channel.
2. What is the difference between calling cert.verify(caKey) and validating with CertPathValidator?
verify checks only one thing: that the certificate's signature was made by the private key matching caKey. PKIX validation also checks that the path ends at a trust anchor, that every certificate is within its validity period at the given date, that issuers are marked as CAs (basic constraints) and allowed to sign certificates (key usage), that names chain correctly, policy and name constraints, and optionally revocation. Skipping those checks leads to accepting expired, revoked or improperly issued certificates.
3. A JAR was signed three years ago with a certificate that expired last month. jarsigner now warns about it. What would have avoided this?
Timestamping. Signing with -tsa <url> makes a timestamping authority countersign the signature with the signing time. Verifiers can then confirm the signature was made while the certificate was valid, so it stays valid after the certificate expires (until the TSA's own certificate expires).
4. Your code opens a signed JAR with new JarFile(f, true) and calls getCodeSigners() on an entry before reading it. It returns null. Why?
Verification is lazy: a JarFile verifies each entry while its content is read, and the signer information is set only after the entry has been read completely, so the digest could be compared. Read the entry's input stream to the end first, then call getCodeSigners(). If the content was tampered with, reading throws SecurityException.
5. Which keytool commands would a CA and a user run to go from "user has a key pair" to "user has a CA-signed certificate in their key store"?
The user runs keytool -certreq to create a certificate signing request from their key entry. The CA checks the user's identity and runs keytool -gencert -infile user.req -outfile user.cer with its own key. The user then imports the CA's root certificate (-importcert -alias ca) if it is not already trusted, and imports the reply under the same alias as their key (-importcert -alias user -file user.cer), which replaces the self-signed certificate with the CA-signed chain.
Previous: Digital Signatures in Java: Signing and Verifying with RSA, EdDSA and ML-DSA
Next: Symmetric Encryption in Java: AES-GCM, Key Generation and Cipher Streams
Related reading

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.