Skip to content

Checking your reading list…

Retry verification

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Java E-Contract Signing: The Real Challenge Is Guaranteeing Immutability After Signature

Java E-Contract Signing: The Real Challenge Is Guaranteeing Immutability After Signature

This article details the architectural decisions for building a tamper-proof electronic contract signing system in Java, covering immutable contract versioning, content hashing, signing sessions, concurrency control, multi-party workflow, step-up authentication, audit trails, and why PDF generation is the simplest part.

Freeze the Contract Before Any Signature

The initial requirement seemed simple: generate a PDF, let both parties sign online, and download the signed document. A demo could be built in a day by pasting a signature image onto the last page of a PDF and storing it in object storage. However, production concerns quickly emerged: can an admin change the amount after one party signs? Can content be altered between signatures? Can the same link be used twice? Who does the SMS code verify? Can a signature image be copied to another contract? What if a third-party platform callbacks twice? The core question: six months later, how do we prove the user signed exactly the contract now in the database?

The first version used a single contract table with a status flow DRAFT → SIGNING → SIGNED. During SIGNING, fields like amount and content were still editable. This meant Party A could sign at 10:01, an admin could change the amount at 10:03, and Party B would see a different contract at 10:05, yet the database would only show a final SIGNED status with no record of the intermediate change.

The solution was to introduce an explicit "Publish Signing Version" action. Once a contract enters the signing flow, the system creates an immutable ContractVersion record:

create table contract_version (
  id bigint primary key,
  contract_id bigint not null,
  version_no int not null,
  document_url varchar(500) not null,
  document_hash varchar(128) not null,
  status varchar(32) not null,
  created_at datetime not null,
  unique key uk_contract_version (contract_id, version_no)
);

Signing now targets a specific contract_version_id (e.g., 30012) rather than a mutable contract_id. A contract can have multiple versions, but each signature is bound to one fixed version.

The Signed Object Is a Content Hash, Not a File Name

Storing only the PDF URL (e.g., contracts/10086/v3.pdf) is insufficient because object storage files can be overwritten. When creating a signing version, the system computes a SHA-256 hash of the file content:

public String sha256(InputStream input) throws Exception {
  MessageDigest digest = MessageDigest.getInstance("SHA-256");
  byte[] buffer = new byte[8192];
  int len;
  while ((len = input.read(buffer)) != -1) {
    digest.update(buffer, 0, len);
  }
  return HexFormat.of().formatHex(digest.digest());
}

The hash (e.g., 9c4f8a3b...) is saved in document_hash. Every signing operation must bind this hash. A SigningTarget record captures the version ID and hash:

public record SigningTarget(
  Long contractVersionId,
  String documentHash
) {}

Later, anyone can verify integrity by re-hashing the current file and comparing it to the stored hash. A single byte change produces a different hash, proving the document was frozen at signing time.

Signing Links Must Be Temporary Credentials, Not Bare IDs

Many systems send links like https://xxx.com/sign/10086 where 10086 is the contract ID. This is dangerous because the ID does not encode which signing round, who should sign, which version, or when the link expires. The author introduced a SigningSession table:

create table signing_session (
  id bigint primary key,
  session_token varchar(128) not null,
  contract_version_id bigint not null,
  signer_id bigint not null,
  signer_role varchar(32) not null,
  status varchar(32) not null,
  expires_at datetime not null,
  completed_at datetime null,
  unique key uk_signing_token (session_token)
);

Users receive a random token (e.g., /sign/8FqA9xK2...). The backend validates the session: it must exist, not be expired, and have status PENDING. The link is a one-time, time-limited credential.

Prevent Duplicate Signatures at the Database Level

Front-end double-clicks can send two concurrent requests. A simple existsBySessionId check followed by save fails under concurrency because both threads may see exists = false. The fix is a unique constraint on signing_session_id in the signature table:

create table contract_signature (
  id bigint primary key,
  signing_session_id bigint not null,
  signer_id bigint not null,
  document_hash varchar(128) not null,
  signed_at datetime not null,
  unique key uk_signature_session (signing_session_id)
);

The Java method uses a conditional update to ensure only one completion succeeds:

@Transactional
public void completeSigning(Long sessionId, SignCommand command) {
  SigningSession session = signingSessionRepository.findById(sessionId).orElseThrow();
  if (session.getStatus() != SigningStatus.PENDING) return;
  signatureRepository.save(ContractSignature.create(session, command));
  int updated = signingSessionRepository.completeIfPending(sessionId, Instant.now());
  if (updated != 1) throw new ConcurrentSigningException();
}

The principle: the database guarantees a SigningSession can complete only once.

Multi-Party Signing Requires Explicit Order and Per-Signer State

For a flow like Party A → Party B → Platform Review, a simple SIGNED/UNSIGNED flag is insufficient. The author created a contract_signer table with individual status and order:

create table contract_signer (
  id bigint primary key,
  contract_version_id bigint not null,
  signer_id bigint not null,
  signer_role varchar(32) not null,
  sign_order int not null,
  status varchar(32) not null,
  signed_at datetime null
);

Example states:

1 PARTY_A PENDING
2 PARTY_B WAITING
3 REVIEWER WAITING

When Party A signs, their status becomes SIGNED and Party B transitions from WAITING to PENDING. The backend checks both session.status == PENDING and signer.getStatus() == SignerStatus.PENDING to prevent premature signing.

A Signature Image Is Not the Signature Event

Handwritten signature images ( signature.png) pasted into PDFs only prove an image exists, not that a specific user confirmed a specific document at a specific time. Images can be copied from Contract A to Contract B. The real evidence is a SignatureEvidence record capturing:

public record SignatureEvidence(
  Long signerId,
  Long contractVersionId,
  String documentHash,
  String signingSessionId,
  String authenticationMethod,
  String ip,
  String deviceId,
  Instant signedAt
) {}

The combination of who, when, via what authentication, against which documentHash, confirmed forms the probative evidence; the image is merely a visual representation.

Step-Up Authentication Before High-Value Actions

Even if a user is logged in, the author recommends re-verifying identity immediately before signing (SMS OTP, TOTP, Passkey, enterprise 2FA). A login session may be hours old; the device might be unattended. A

securityService.requireRecentStrongAuth(userId, Duration.ofMinutes(5))

call ensures the person clicking "Sign" is the same person who just authenticated. This treats signing as a high-value action akin to changing a phone number or adding a login credential.

Disable Backend Editing Once Signing Starts

Admins often want an "Edit" button to fix typos during signing. The author forbids this: once any signer has signed document_hash = A, that version is immutable. If a correction is needed, the correct process is: Version 3 → VOID, then generate Version 4 → SIGNING, and have all parties re-sign. The database retains V3 voided and V4 current. Overwriting v3.pdf in place would break the hash chain and invalidate all prior evidence.

Third-Party Callbacks Must Be Idempotent

When integrating with external e-sign platforms, callbacks (e.g., POST /callbacks/signature with { "signingId": "S20261123001", "status": "COMPLETED" }) may be retried due to network timeouts. Processing each callback naively (update status, send notification, calculate commission) would duplicate side effects. The solution is idempotency via a unique key on (provider, event_id) or a conditional update:

UPDATE contract_signer SET status = 'SIGNED', signed_at = ? WHERE id = ? AND status = 'PENDING';

If affectedRows = 0, the event was already handled and no further business logic runs.

Final Contract State Should Not Rely on Race-Prone Checks

Checking "are all signers done?" in application code ( countByContractVersionIdAndStatusNot(versionId, SIGNED) == 0) fails when the last two signers complete simultaneously. The robust approach moves the final state transition into a single conditional SQL statement:

UPDATE contract_version v
SET status = 'SIGNED', completed_at = NOW()
WHERE v.id = ?
  AND v.status = 'SIGNING'
  AND NOT EXISTS (
    SELECT 1 FROM contract_signer s
    WHERE s.contract_version_id = v.id
      AND s.status <> 'SIGNED'
  );

Alternatively, an event-driven collector can confirm completion. The principle: signing completion is a business fact, not a coincidence of concurrent checks.

Re-Verify the Final Archived PDF

After all signatures, the system generates a final archive PDF containing the original text, signature images, timestamps, signer info, and an evidence page. The author computes a final_document_hash distinct from the original_hash. The original hash proves what all parties agreed to; the final hash proves what the system archived. Both are stored so any later corruption or replacement of the archive file is immediately detectable.

Audit Logs Must Capture Full Context for Future Disputes

Ordinary operation logs ("user signed successfully") are insufficient. The audit record includes:

contractVersionId, signingSessionId, signerId, signerRole, documentHash, authenticationMethod, deviceId, ip, userAgent, signedAt, providerRequestId, providerEventId, result

. When a dispute arises years later, the system must answer: who signed? which version? what authentication method? was the file altered? what did the third-party platform return? The goal is not to show "SIGNED" now, but to reconstruct the complete event years later.

The PDF Is the Simplest Layer; the State Machine Is the Skeleton

The team initially thought the core work was PDF generation, placing signatures, stamping, and downloading. In reality, the PDF is just the final presentation. The true complexity lies in the state chain:

DRAFT → VERSION_FROZEN → SIGNING → PARTIALLY_SIGNED → SIGNED → ARCHIVED

with additional terminal states EXPIRED, VOID, REJECTED. Every state must define who can enter, what conditions allow exit, and which data remains mutable. For example:

DRAFT: content editable
SIGNING: content frozen
SIGNED: all evidence frozen
VOID: old version permanently disabled

This state machine is the system's backbone.

Electronic Signing Binds Identity, Time, Version, and Evidence — Not Just a Name

Writing "Zhang San" into a PDF is trivial. The real confirmation is: Zhang San, at a specific time, via a specific authentication method, against documentHash=A, expressed consent. That tuple is a complete piece of evidence. When someone says "e-contract is just pasting a signature on PDF," the author asks: "If I change 100,000 to 1,000,000 after you sign, how does the system prove you didn't sign that amount?" If that question cannot be answered, a pretty PDF with a signature image is not a reliable signing system. The Java backend's job is not to draw signatures, but to bind document, identity, version, time, state, and evidence together so that the moment a user clicks "Confirm Sign", the system records not an image, but a provable fact.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

Published

AI-assisted summary

Report an issue with this article
JavaConcurrency ControlDatabase DesignImmutabilityDigital SignaturesSHA-256Audit TrailElectronic Contracts

Reader feedback

Was this useful?

Useful0

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion