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());
}
}
}
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!