LearnFrenzy
Sign in Take a free test

Serialization · Serialization Programs · Question 9

Bank ledger with checksum validation in Java Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

Write a Ledger whose writeObject stores the entries and a checksum, and whose readObject recomputes the checksum and rejects tampered data with InvalidObjectException; show a valid load and a tampered one.

Solution
Main.java
import java.io.*;
import java.util.ArrayList;
import java.util.List;

class Ledger implements Serializable {
    private static final long serialVersionUID = 1L;
    transient ArrayList<Long> entries = new ArrayList<>();       // amounts in paise
    static boolean tamper = false;                               // used only to simulate corruption

    @Serial private void writeObject(ObjectOutputStream out) throws IOException {
        out.defaultWriteObject();
        out.writeInt(entries.size());
        long sum = 0;
        for (long e : entries) { out.writeLong(tamper && sum == 0 ? e * 10 : e); sum += e; }
        out.writeLong(sum);                                      // checksum of the TRUE values
    }

    @Serial private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        in.defaultReadObject();
        int n = in.readInt();
        entries = new ArrayList<>();
        long sum = 0;
        for (int i = 0; i < n; i++) { long e = in.readLong(); entries.add(e); sum += e; }
        if (sum != in.readLong()) throw new InvalidObjectException("checksum mismatch");
    }

    long balance() { return entries.stream().mapToLong(Long::longValue).sum(); }
}

public class Main {
    static byte[] save(Object o) throws IOException {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {
            out.writeObject(o);
        }
        return bytes.toByteArray();
    }

    static Object load(byte[] data) throws IOException, ClassNotFoundException {
        try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data))) {
            return in.readObject();
        }
    }

    public static void main(String[] args) throws Exception {
        Ledger l = new Ledger();
        l.entries.addAll(List.of(500000L, -125050L, 2000L));
        Ledger ok = (Ledger) load(save(l));
        System.out.println("balance Rs " + ok.balance() / 100.0 + ", entries " + ok.entries.size());
        Ledger.tamper = true;
        try {
            load(save(l));
        } catch (InvalidObjectException e) {
            System.out.println("rejected: " + e.getMessage());
        }
    }
}

Output Verified by compiling and running

balance Rs 3769.5, entries 3
rejected: checksum mismatch

Custom hooks can add integrity checks to the serialized form; readObject throws InvalidObjectException when the data does not add up.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links