跳到主要内容
基础知识

Java Code Signing Certificate: JAR Signing and Verification

java code signing certificate — Java Code Signing Certificate: JAR Signing and Verification
核心结论

A Java code signing certificate is an X.509 certificate with the codeSigning extended key usage (EKU 1.3.6.1.5.5.7.3.3) that you use with keytool and jarsigner to sign JAR files; OV code signing certificates commonly list at $200–$500 per year and validate in 1–3 business days. Generate a 3072-bit RSA key and CSR with `keytool -genkeypair -alias codesign -keyalg RSA -keysize 3072 -sigalg SHA256withRSA -storetype PKCS12 -keystore codesign.p12` and `keytool -certreq -alias codesign -file codesign.csr -keystore codesign.p12`. Sign with `jarsigner -digestalg SHA-256 -sigalg SHA256withRSA -tsa http://timestamp.digicert.com -keystore codesign.p12 app.jar codesign`; the RFC 3161 timestamp keeps signatures verifiable after the certificate expires. Verify with `jarsigner -verify -verbose -certs -strict app.jar`; look for `jar verified.` and a `Timestamp:` line, and inspect `META-INF/*.SF` and `META-INF/*.RSA`. A Java code signing certificate cannot be used as a TLS/SSL certificate for HTTPS; TLS certificates use serverAuth EKU and are deployed on port 443, while code signing certificates sign artifacts.

What Is a Java Code Signing Certificate and Why Do JARs Need One?

A java code signing certificate is an X.509 v3 certificate issued to a legal entity — a company or an individual developer identity vetted by a public CA — that carries Key Usage: digitalSignature and Extended Key Usage: codeSigning (OID 1.3.6.1.5.5.7.3.3). Per RFC 5280 §4.2.1.12, that EKU extension restricts the certificate to one purpose, so the same key cannot be used for TLS. The certificate binds the organization name in the Subject DN to the public key whose private key signs the JAR, which is exactly the attribution a JAR file otherwise lacks.

Why do JARs need one? A JAR is just a ZIP archive with META-INF/MANIFEST.MF. When you sign, jarsigner writes a per-entry SHA-256 digest into the manifest, a META-INF/*.SF signature file, and a META-INF/*.RSA (or .EC/.DSA) signature block holding the PKCS#7 SignedData. Strip those three and Java still verifies integrity via checksums — it simply cannot tell you who built the artifact.

# Sign (jarsigner ships with JDK 8 through JDK 21+; -tsa is an RFC 3161 timestamp)
jarsigner -keystore release.p12 -storetype PKCS12 
  -digestalg SHA-256 -sigalg SHA256withRSA    # SHA-1/MD5 rejected by default since JDK 9
  -tsa http://timestamp.digicert.com          # countersigned into the .RSA block
  app.jar "CN=Example Ltd, O=Example Ltd, C=GB"

# Inspect what the signature actually asserts
jarsigner -verify -verbose -certs app.jar
keytool -printcert -jarfile app.jar             # shows EKU: [1.3.6.1.5.5.7.3.3] codeSigning

Does signing make java -jar show a padlock? No. Standalone execution performs no publisher UI and no revocation lookup, and Windows SmartScreen or macOS Gatekeeper ignore JAR signatures entirely — signing a JAR is not OS-level trust. Enforcement lives elsewhere: legacy applets and Java Web Start, enterprise runtimes, Java agents, and distribution platforms that check the signer DN before loading a plugin.

Weak algorithms now fail hard. JDK 9+ reads jdk.jar.disabledAlgorithms from $JAVA_HOME/conf/security/java.security (JDK 8: $JAVA_HOME/lib/security/java.security); the default blocks MD2, MD5 and SHA-1, and jarsigner exits with jarsigner: unable to sign jar: java.security.NoSuchAlgorithmException: SHA1 usage rejected, see the jdk.jar.disabledAlgorithms security property.

Always add -tsa. Without it, jarsigner -verify warns “This jar contains signatures that do not include a timestamp” and fails once the signer certificate expires, even though the signature predates expiry.

Aspect Java code signing cert TLS server cert
EKU OID 1.3.6.1.5.5.7.3.3 (codeSigning) 1.3.6.1.5.5.7.3.1 (serverAuth)
Key Usage digitalSignature digitalSignature, keyEncipherment
Consumer jarsigner / JVM classloader Browser, OpenSSL, curl
Validity 1–3 years typical ≤ 398 days (CA/B Forum)

What both share is the plumbing you already know from TLS: a CSR (keytool -certreq instead of openssl req), an intermediate chain embedded in the signature block, and RFC 5280 path validation with CRL/OCSP revocation. That is why a java code signing certificate belongs in the same lifecycle tooling as your TLS inventory — same CA, same expiry alarms, different EKU.

How Do You Choose a Java Code Signing Certificate: OV vs EV, Cost, and Validity?

OV or EV — which one do you actually need? Standard OV (organization-validated) Java code signing certificates typically list at $200–$500/year and the CA completes legal-entity vetting in 1–3 business days. EV (extended validation) certificates list at $300–$700/year, take 3–7 business days, and are issued onto a FIPS 140-2 Level 2 USB token or HSM so the private key is non-exportable. That last point matters more than the price gap: since CA/Browser Forum Code Signing Baseline Requirements v3.0 (effective 1 June 2023), all code signing subscriber keys must be generated and stored in FIPS 140-2 Level 2 or Common Criteria EAL4+ hardware — EV just bundles the token. Also remember Java shows the same “Publisher:” line in the Security dialog for OV and EV; the practical EV benefit is reputation with Windows SmartScreen, not extra jarsigner UI.

Criterion OV code signing EV code signing
Typical list price $200–$500/yr $300–$700/yr
Issuance time 1–3 business days 3–7 business days
Key storage FIPS 140-2 L2 token or HSM FIPS 140-2 L2 token/HSM, non-exportable
CI signing Token/HSM or cloud signing service Token/HSM or cloud signing service
Best for Internal tools, smaller ISVs Public desktop/mobile distribution

How long can you hold it? Public code signing certificates are commonly issued for 1–3 years; CSBR §6.3.2 caps subscriber certificate validity (historically 39 months), so plan renewal and always timestamp signatures with an RFC 3161 TSA — timestamps keep your JARs verifiable after the certificate expires.

Which algorithm? Use RSA 3072 or 4096 with SHA256withRSA for the broadest Java compatibility. ECDSA P-256/P-384 (SHA256withECDSA/SHA384withECDSA) works on modern JDKs but fails on older runtimes whose jdk.jar.disabledAlgorithms or provider set doesn’t cover EC. Generate the key and CSR directly with keytool (JDK 9+ defaults to PKCS#12 keystores):

# 1) Generate a 3072-bit RSA key pair in a PKCS#12 keystore
keytool -genkeypair -alias codesign -keyalg RSA -keysize 3072 
  -sigalg SHA256withRSA 
  -dname "CN=Acme Corp, O=Acme Corp, L=Springfield, ST=IL, C=US" 
  -validity 1095 -storetype PKCS12 -keystore acme.p12 -storepass changeit

# 2) Emit the CSR the CA validates against your legal registration
keytool -certreq -alias codesign -keystore acme.p12 -storepass changeit 
  -sigalg SHA256withRSA -file acme.csr

What goes in the -dname? The CA validates your registered legal organization name, physical address and phone — so O= must match the registration exactly. Unlike a DV TLS certificate from Let’s Encrypt (which validates domain control only), code signing never involves a domain name.

What should you ask for at checkout? Request a PKCS#12 (.p12/.pfx) or JKS keystore for CI, or a PKCS#11 token for EV; ask the CA to ship the intermediate CA certificate in the reply chain and to confirm the RFC 3161 timestamp URL. Then sign and verify:

# Import the full chain returned by the CA
keytool -importcert -noprompt -alias codesign -keystore acme.p12 
  -storepass changeit -file acme-fullchain.pem -trustcacerts

# Sign with an RFC 3161 timestamp (jarsigner -tsa; -tsadigestalg since JDK 9)
jarsigner -keystore acme.p12 -storepass changeit -sigalg SHA256withRSA 
  -digestalg SHA-256 -tsa http://timestamp.digicert.com -tsadigestalg SHA-256 
  app.jar codesign

# Verify
jarsigner -verify -verbose -certs app.jar

Procurement checklist: codeSigning EKU present, digitalSignature Key Usage, SHA-256 signatures only, private-key exportability if your CI needs a file-based key, token/HSM support, and renewal pricing — list prices vary by CA and volume.

How Do You Request a Java Code Signing Certificate with keytool and a CSR?

Requesting a Java code signing certificate is a three-artifact dance: a private key that never leaves your machine, a PKCS#10 CSR (RFC 2986) that does, and a CA reply that must be imported on top of the existing alias. Getting the order wrong is the single most common reason `keytool -importcert` fails with keytool error: java.lang.Exception: Certificate reply does not match the certificate request.

Start by creating the keypair in a PKCS#12 keystore — since JDK 9 the default keystore.type in $JAVA_HOME/conf/security/java.security is PKCS12, but state it explicitly so the command behaves identically on JDK 8:

keytool -genkeypair -alias codesign 
  -keyalg RSA -keysize 3072 -sigalg SHA256withRSA 
  -validity 730 
  -dname 'CN=Acme Corp, O=Acme Corp, L=Springfield, ST=IL, C=US' 
  -ext KU=digitalSignature -ext EKU=codeSigning 
  -storetype PKCS12 -keystore codesign.p12
# -validity 730 is only the placeholder self-signed cert; the CA sets the real
#   validity (Code Signing BRs cap subscriber certs at 39 months)
# -ext EKU=codeSigning matters for local jarsigner testing only — the CA issues
#   the production cert with the EKU and keyUsage=digitalSignature already set

Then emit the CSR and read it back before you upload anything:

keytool -certreq -alias codesign -file codesign.csr 
  -keystore codesign.p12 -sigalg SHA256withRSA

keytool -printcertreq -file codesign.csr
# PKCS #10 Certificate Request (Version 1.0)
# Subject: CN=Acme Corp, O=Acme Corp, L=Springfield, ST=IL, C=US
# Key: 3072-bit RSA key, Signature algorithm name: SHA256withRSA

Check the O= field and key size here; a CA will happily issue against a typo’d organization name. Reject any flow that asks for SHA-1 — JDK 17+ ships jdk.jar.disabledAlgorithms=MD2, MD5, SHA1 in java.security, so SHA-1-signed JARs fail verification on modern runtimes.

Import the chain before the reply, otherwise keytool cannot build a path to a trusted root:

keytool -importcert -alias acme-root -file root.crt -keystore codesign.p12
keytool -importcert -alias acme-intermediate -file intermediate.crt -keystore codesign.p12
keytool -importcert -alias codesign -file codesign.crt -keystore codesign.p12
# last command replaces the self-signed entry; never use -alias for a new name
keytool -list -v -alias codesign -keystore codesign.p12
# Certificate chain length: 3
# Subject Public Key Algorithm: 3072-bit RSA key
# Signature algorithm name: SHA256withRSA
# Certificate fingerprints: SHA256: 9F:...
Artifact Holds private key? Send to CA? Purpose
codesign.p12 Yes Never Signing + chain storage
codesign.csr No Yes (PEM) Public key + DN proof
codesign.crt No — CA reply to import
keytool flag Default Recommended
-keysize (RSA) 2048 3072 or 4096
-validity 90 days 730 (placeholder only)
-storetype PKCS12 (JDK 9+) PKCS12 explicitly

Finally, treat the keystore as a credential: chmod 600 codesign.p12, copy it to an offline vault, and store the password in a secrets manager. In CI, pass -storepass:env KEYSTORE_PASS rather than inlining -storepass, so the secret never lands in shell history or build logs — the same hygiene that applies to any TLS private key.

How Do You Sign a JAR with jarsigner and a Java Code Signing Certificate?

Assuming your Java code signing certificate and its private key already sit in a PKCS#12 keystore, one command does digesting, signing, and timestamping. This is the full, copy-pasteable form:

# Sign app.jar into a NEW file, leaving the original build artifact untouched
jarsigner 
  -keystore codesign.p12 -storetype PKCS12 
  -digestalg SHA-256 -sigalg SHA256withRSA 
  -tsa http://timestamp.digicert.com 
  -signedjar app-signed.jar 
  app.jar codesign          # app.jar = input JAR, codesign = keystore alias

Why bother with -signedjar? Without it, jarsigner rewrites app.jar in place, so a failed run leaves you with a half-processed artifact and no clean input to retry against. Writing to a new name keeps the build output immutable and makes the checksum step below meaningful.

What does the timestamp actually buy you? Without one, the signature carries no proof of when it was made, so verifiers reject the JAR once the certificate expires. With an RFC 3161 timestamp, the TSA’s token proves the signing happened inside the validity window. -tsa URL talks HTTP/HTTPS (outbound TCP 80/443 must be open); if the TSA is unreachable, signing fails rather than silently skipping the timestamp — behind a corporate proxy add -J-Djava.net.useSystemProxies=true. For air-gapped builds, -tsacert alias timestamps using a TSA certificate already in the keystore, with no network call at all.

Option Effect Default when omitted
-signedjar out.jar Writes signed output to out.jar Input JAR modified in place
-tsa URL RFC 3161 timestamp fetched over HTTP(S) No timestamp
-tsacert alias Timestamp from a keystore TSA cert —
-sigfile NAME Base name for META-INF/NAME.SF and NAME.RSA Alias, uppercased
-digestalg / -sigalg Digest and signature algorithms SHA-256 / SHA256withRSA on JDK 8+; SHA-1 on JDK 7

What files does the alias produce? codesign yields META-INF/CODESIGN.SF plus META-INF/CODESIGN.RSA (or .EC for EC keys). Use -sigfile ACME to control that base name — but keep it to 8 characters, because older jarsigner releases truncate longer names, which silently breaks tooling that looks for a fixed name.

Which algorithms should you pin? State -digestalg SHA-256 -sigalg SHA256withRSA explicitly; for EC keys use SHA256withECDSA. JDK 7 and early JDK 8 updates defaulted to SHA-1, and current JDKs deny it through jdk.jar.disabledAlgorithms in $JAVA_HOME/conf/security/java.security, so SHA-1-signed JARs now verify as unsigned. Note that public TLS CAs such as Let’s Encrypt do not issue code signing certificates — you need a CA whose EKU includes codeSigning.

Do nested JARs get signed? No. Per Oracle’s jarsigner reference, only the outer JAR and its manifest entries are signed; JARs embedded in a fat JAR stay untouched. Sign every distributable artifact separately with the same certificate so the release shares one identity.

# Always verify before publishing; -certs prints the signer chain
jarsigner -verify -verbose -certs app-signed.jar
sha256sum app-signed.jar

Re-signing an already-signed JAR replaces the META-INF signature files rather than stacking a second signature. Typical failures you will hit:

jarsigner: Certificate chain not found for: codesign.  codesign must reference
  a valid KeyStore key entry containing a private key and corresponding public
  key certificate chain.
jarsigner: unable to sign jar: java.net.SocketTimeoutException: connect timed out

The first means the alias points at a trusted-cert entry instead of a key entry (import the full chain with -importcert); the second is the TSA being blocked by a firewall.

Java Code Signing Certificate Configuration Examples for CI, PKCS#12, and Hardware Tokens

Wondering how a java code signing certificate actually gets applied in a headless CI runner? The three configurations below cover the realistic cases: a PKCS#12 bundle held in CI secrets, a PKCS#11 hardware token, and Maven’s plugin wrapper. All examples target JDK 21; the :env password modifiers require JDK 9+ per the jarsigner man page.

PKCS#12 in CI — what does the command look like? Keep the keystore and both passwords in CI secrets, and let jarsigner read them from the environment so they never appear in argv or ps output:

# JDK 9+ :env modifiers keep passwords out of the process table
jarsigner 
  -keystore "$KEYSTORE_PATH" 
  -storetype PKCS12 
  -storepass:env KEYSTORE_PASS 
  -keypass:env KEY_PASS 
  -digestalg SHA-256 
  -sigalg SHA256withRSA 
  -tsa "$TSA_URL" 
  -signedjar out/app.jar in/app.jar codesign
# codesign = alias of the private key entry inside the PKCS#12 file
# digestalg default is SHA-256 on modern JDKs; sigalg defaults from the key type

If the key password is wrong, expect jarsigner: unable to sign jar: java.security.UnrecoverableKeyException: Cannot recover key; if the alias is wrong, jarsigner: Certificate chain not found for: codesign. Both usually mean the PKCS#12 was exported with a different key password than the store password.

PKCS#11 token — how do I point SunPKCS11 at the right slot? Create a provider config and select the token by zero-based index:

# pkcs11.cfg — Debian/Ubuntu OpenSC path; RHEL uses /usr/lib64/opensc-pkcs11.so
name = codesign
library = /usr/lib/x86_64-linux-gnu/pkcs11/opensc-pkcs11.so
slotListIndex = 0
jarsigner -keystore NONE -storetype PKCS11 
  -providerClass sun.security.pkcs11.SunPKCS11 
  -providerArg pkcs11.cfg 
  -tsa http://timestamp.digicert.com 
  app.jar codesign
# jarsigner prompts for the token PIN; use -storepass:env PIN only if your PIN policy allows it

For EV tokens, enforce a PIN policy and audit token use — the private key is non-exportable, so CI must reach the token or its signing service. A wrong library path surfaces as java.security.KeyStoreException: PKCS11 not found.

Maven example. maven-jarsigner-plugin 3.0.0 binds signing to package, so the artifact is signed before install/deploy:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-jarsigner-plugin</artifactId>
  <version>3.0.0</version>
  <executions>
    <execution>
      <id>sign</id>
      <phase>package</phase>
      <goals><goal>sign</goal></goals>
      <configuration>
        <keystore>${env.KEYSTORE_PATH}</keystore>
        <storetype>PKCS12</storetype>
        <storepass>${env.KEYSTORE_PASS}</storepass>
        <keypass>${env.KEY_PASS}</keypass>
        <alias>codesign</alias>
        <digestalg>SHA-256</digestalg>
        <sigalg>SHA256withRSA</sigalg>
        <tsa>${env.TSA_URL}</tsa>
      </configuration>
    </execution>
  </executions>
</plugin>
Approach Secret location CI fit Typical failure
PKCS#12 file Keystore file + env passwords High; mount read-only Wrong keypass or alias
PKCS#11 token Token PIN, key non-exportable Medium; needs token/HSM reachable Wrong slotListIndex or provider path
Maven plugin Delegates to jarsigner High; lifecycle-bound Plugin version or phase misconfigured

Container and timestamp resilience. Pin the base image and log the tool version so signatures are auditable:

FROM eclipse-temurin:21-jdk
RUN apt-get update && apt-get install -y --no-install-recommends opensc 
 && rm -rf /var/lib/apt/lists/*
RUN jarsigner -version && java -version

jarsigner accepts only one -tsa URL, so wrap the signing call in a retry loop with a fallback TSA. A curl -I check only proves reachability; validate RFC 3161 behavior with OpenSSL’s ts client before the release window. For secret hygiene, prefer -storepass:env/-keypass:env, mount the keystore read-only, and rotate the keystore password if a log or artifact exposes it — the same discipline applies to any java code signing certificate used in shared build infrastructure.

Java Code Signing Certificate vs TLS/SSL and EV Code Signing: Comparison Table

Can you reuse a TLS certificate as a java code signing certificate, and does an EV code signing certificate give you a browser-style padlock for java -jar? No on both counts — the extensions baked into the certificate decide what the platform will accept, and Java’s runtime policy (not a browser UI) decides whether a signature is trusted. Here is how the three products actually differ.

Aspect Java code signing certificate TLS/SSL certificate EV code signing certificate
Primary use Sign JARs/artifacts with jarsigner HTTPS on port 443 Sign artifacts with a hardware-protected key
EKU codeSigning (1.3.6.1.5.5.7.3.3) serverAuth (1.3.6.1.5.5.7.3.1) codeSigning
Key Usage digitalSignature digitalSignature, keyEncipherment (RSA) digitalSignature
Validation Organization (OV) Domain (DV), organization (OV/EV) Extended organization + hardware
Private key storage PKCS#12 file or token Server file, token, or HSM FIPS 140-2 Level 2 token/HSM (mandatory)
Typical list price $200–$500/year DV $0–$100; OV $100–$300; EV $200–$500/year $300–$700/year
Max public validity 1–3 years (historically 39 months) 398 days for public TLS per CA/B Forum BRs 1–3 years
Trust signal Java/OS policy, not a browser padlock Browser padlock Java/OS policy, token-backed

The mismatch surfaces at verification time: jarsigner reads the signer’s EKU and emits Warning: This jar contains entries whose signer certificate's ExtendedKeyUsage extension doesn't allow code signing. when the codeSigning OID is missing — a common symptom after someone signs with a TLS cert. With -strict that warning becomes exit code 4, which is exactly the failure a CI pipeline should catch.

# 0) Sign: SHA-256 digests + RFC 3161 timestamp so the signature outlives the cert
jarsigner -keystore signing.p12 -storetype PKCS12 
  -sigalg SHA256withRSA -digestalg SHA-256 
  -tsa https://timestamp.digicert.com app.jar codesign-alias
# JDK 9+ disables SHA-1 JAR digests via jdk.jar.disabledAlgorithms in
# $JAVA_HOME/conf/security/java.security — re-sign legacy JARs before upgrading.

# 1) Read the EKU with OpenSSL 3.x: TLS server cert vs code signing cert
openssl x509 -in codesign.crt -noout -text | grep -A1 "Extended Key Usage"
#   TLS  -> TLS Web Server Authentication (1.3.6.1.5.5.7.3.1)
#   Code -> Code Signing (1.3.6.1.5.5.7.3.3)

# 2) Same check straight from the signed artifact
keytool -printcert -jarfile app.jar | grep -A2 ExtendedKeyUsage

# 3) Verify and fail CI on warnings (EKU mismatch, weak algorithm, expiring cert)
jarsigner -verify -verbose -certs -strict app.jar
# exit 0 = verified, 4 = warnings present, 1 = verification error

Both worlds share one path-validation algorithm — RFC 5280 §6 — but not the same anchors or revocation model. TLS relies on browser root programs plus Certificate Transparency (RFC 6962); JAR verification relies on the JDK’s cacerts trust store and OS policy, with no CT log. Per Let’s Encrypt’s documentation, Let’s Encrypt issues TLS/SSL certificates for HTTPS only and does not issue code signing certificates, so a java code signing certificate must come from a CA that actually asserts the codeSigning EKU.

Validity and cost diverge too: public TLS is capped at 398 days by the CA/Browser Forum Baseline Requirements, while code signing certificates are sold on 1–3 year terms because revocation, not expiry, is the primary control. EV code signing raises the identity bar and keeps the key in a FIPS 140-2 Level 2 token or HSM, yet java -jar still shows no browser-style trust indicator — Java runtime policy decides. That makes RFC 3161 timestamps more valuable than term length, and makes three-year total cost the right comparison: multi-year and renewal discounts routinely flip the first-year ranking between the $200–$500 OV and $300–$700 EV tiers.

Common Java Code Signing Certificate Errors and Troubleshooting

Nearly every failure in this list traces back to one of three gaps: the JAR path jarsigner actually resolved, an incomplete chain in the keystore, or a signature with no RFC 3161 timestamp. Oracle’s jarsigner reference is explicit that exit code 1 means “signing or verification failed” — read the message, because the exit code alone won’t tell you which of the three it was.

Why does jarsigner say “unable to open jar file”? The tool resolves the path relative to your current directory, refuses to create missing parent directories for -signedjar, and emits the identical message when the working directory is read-only (it writes a temp file beside the input).

# Create the output directory FIRST — jarsigner will not mkdir -p for you
mkdir -p build/signed
jarsigner -keystore codesign.p12 -storetype PKCS12 
  -signedjar build/signed/app.jar build/app.jar codesign
# -signedjar keeps the original intact; omit it to sign in place

Why do I get “Certificate chain not found” or “unable to find valid certification path”? A missing intermediate is the single most common java code signing certificate problem: your keystore holds the leaf plus root but not the CA that issued the leaf. Import intermediates in order, then confirm the chain:

keytool -importcert -alias intermediate -file intermediate.crt 
  -keystore codesign.p12 -storetype PKCS12   # repeat for the root
keytool -list -v -alias codesign -keystore codesign.p12 -storetype PKCS12 | grep "chain length"
# expected: Certificate chain length: 3

Why does verification report “The signer certificate has expired”? The certificate expired after signing and no timestamp proves the signature predates expiry. Re-sign with an RFC 3161 TSA (the -tsa option has no default — omit it and the JAR is timestamp-free):

jarsigner -keystore codesign.p12 -storetype PKCS12 
  -digestalg SHA-256 -sigalg SHA256withRSA 
  -tsa http://timestamp.digicert.com 
  -signedjar build/signed/app.jar build/app.jar codesign
jarsigner -verify -verbose -certs build/signed/app.jar | grep -i timestamp

“SHA-1 is disabled” or “Unsupported algorithm”? Modern JDKs deny SHA-1 through jdk.jar.disabledAlgorithms. Check the file that applies to your runtime — $JAVA_HOME/conf/security/java.security on JDK 9+, $JAVA_HOME/lib/security/java.security on JDK 8 — with grep jdk.jar.disabledAlgorithms, then re-sign using the flags above. jarsigner defaults to SHA-256 on JDK 9+ but older JDK 8 builds still defaulted to SHA-1.

“Timestamping failed”? Prove reachability first with curl -I http://timestamp.digicert.com, allow outbound TCP 80/443, or add -J-Djava.net.useSystemProxies=true for corporate proxies. Offline networks can use -tsacert <tsa-alias> with the TSA certificate already in the keystore.

“Invalid keystore format” or “Alias <name> does not exist”? Match -storetype PKCS12 to the file and enumerate what’s really inside — aliases are case-sensitive, and JKS/PKCS12 are not interchangeable.

Error Root cause Fix
unable to open jar file Bad path, missing parent dir, read-only cwd mkdir -p output dir; use -signedjar
Certificate chain not found Intermediate absent from keystore keytool -importcert; verify chain length 3
signer certificate has expired No RFC 3161 timestamp Re-sign with -tsa
SHA-1 is disabled jdk.jar.disabledAlgorithms -digestalg SHA-256 -sigalg SHA256withRSA
Timestamping failed TSA unreachable / proxy curl -I, -J-Djava.net.useSystemProxies=true, or -tsacert
Alias does not exist Wrong storetype or case keytool -list -keystore codesign.p12 -storetype PKCS12

If you’re troubleshooting alongside TLS certificate chain issues, note the mechanics differ: TLS clients fetch missing intermediates via AIA, whereas jarsigner cannot — the chain must be physically present in the java code signing certificate keystore before signing.

How Do You Verify a JAR Signed with a Java Code Signing Certificate?

Verification answers two separate questions: is the signature cryptographically intact, and is the certificate the exact one you ordered? Oracle’s jarsigner does both in one pass. Run jarsigner -verify -verbose -certs -strict app-signed.jar; success prints jar verified. followed by every entry name. The -strict flag (available since JDK 8) turns warnings into a nonzero exit status — without it, an expired or timestamp-less signature still exits 0, which is why CI gates must use -strict.

Flag What it adds Failure signal to grep for
-verify Default verification, exit 0/1 jar is unsigned
-verbose Per-entry digest status unsigned entries
-certs Prints signer + TSA certificate chains Missing Timestamp: line
-strict Warnings become errors (exit 1) signatures that do not include a timestamp

Next, confirm the archive actually contains a signature block. unzip -l app-signed.jar | grep META-INF should list MANIFEST.MF, CODESIGN.SF, and CODESIGN.RSA (or .EC / .DSA depending on key type). unzip -p app-signed.jar META-INF/MANIFEST.MF shows the per-entry SHA-256-Digest attributes; the .SF file holds the digest of the manifest itself, which is what stops an attacker swapping entries.

Now inspect the signer identity: keytool -printcert -jarfile app-signed.jar prints the chain. Verify the subject organization, the ExtendedKeyUsage containing codeSigning (OID 1.3.6.1.5.5.7.3.3), validity dates, and the SHA-256 fingerprint against your order confirmation.

# Full manual verification sequence (JDK 8u302+, 11, 17, 21)
jarsigner -verify -verbose -certs -strict app-signed.jar   # expect "jar verified."
unzip -l app-signed.jar | grep META-INF                   # MANIFEST.MF, CODESIGN.SF, CODESIGN.RSA
unzip -p app-signed.jar META-INF/MANIFEST.MF | head -20   # per-entry SHA-256-Digest
keytool -printcert -jarfile app-signed.jar                # codeSigning EKU + fingerprint
java -jar app-signed.jar                                  # runtime smoke test

Timestamping matters because a code signing certificate typically lives 1–3 years while your JAR lives longer. If you signed with -tsa https://timestamp.digicert.com (RFC 3161), -verbose -certs output includes a Timestamp: line plus the TSA chain. Its absence means the signature dies when the cert expires.

Finally, test on the oldest JDK you support. JDK 17’s java.security ships jdk.jar.disabledAlgorithms=MD2, MD5, RSA keySize < 1024, DSA keySize < 1024, SHA1 denyAfter 2019-01-01, so a SHA-1-signed JAR that loads on JDK 8 throws SecurityException: invalid SHA-256 signature file digest or a disabled-algorithm error on 17+. -Djava.security.debug=jar traces which provider rejected it.

# CI gate: fail unless verified, signed with codeSigning EKU, and timestamped
jarsigner -verify -strict app-signed.jar | grep -q 'jar verified' || exit 1
jarsigner -verify -verbose -certs app-signed.jar | grep -q 'Timestamp:'   || exit 1
keytool -printcert -jarfile app-signed.jar | grep -q 'codeSigning'        || exit 1
cp app-signed.jar verify-$(date +%F).log ./audit/

No. A Java code signing certificate uses the codeSigning EKU to sign JAR artifacts, while a TLS/SSL certificate uses the serverAuth EKU for HTTPS on port 443. They share CSR, chain, and RFC 5280 validation concepts, but the certificates are not interchangeable.

OV Java code signing certificates commonly list at $200–$500 per year, and EV code signing certificates commonly list at $300–$700 per year. Multi-year and renewal discounts are common, and EV hardware tokens may add shipping or replacement fees.

OV certificates typically validate in 1–3 business days after organization verification, while EV certificates typically take 3–7 business days. Missing phone verification, legal documents, or an unsigned CSR can extend the timeline.

Yes for testing: `keytool -genkeypair` can create a self-signed key with codeSigning EKU, and jarsigner can sign with it. Recipients will not trust the publisher chain, so use a public CA-issued Java code signing certificate for distribution.

The signer chain is missing an intermediate or root certificate, or the verification truststore does not anchor the CA. Import the intermediate and root with `keytool -importcert`, then re-run `jarsigner -verify -verbose -certs`; the warning can affect trust even when the signature integrity check passes.

No. JAR signing provides integrity and publisher identity, but Java does not show a browser-style padlock for standalone `java -jar` execution. OS code-signing policy, enterprise allowlists, and runtime configuration still decide whether the artifact is trusted.

Use the RFC 3161 TSA URL provided by your CA, such as `http://timestamp.digicert.com` or `http://timestamp.sectigo.com`; no single URL is mandatory. Test outbound TCP 80/443 from the build network and keep a fallback TSA URL for release automation.


本文由 sslgood.com 安全团队基于生产环境实战经验撰写,关键结论均经过技术复核。

内容审核

长期从事 SSL/TLS 证书部署与 HTTPS 运维,负责本站证书选型、安装配置与故障排查内容的编写与审核。