Encapsulation
easy 35 minPut the data and the methods that work on it into one unit, and let outside code reach the data only through those methods.
Watch lesson4:51
Secrets in an object
A PIN without a getter, the leaks beside the getter, and why private is not a security border.
The point: for a secret the interface is a question with a yes or no answer. And private stops mistakes of honest code, not an attacker in the same process.
Compare, never reveal
A cash machine must know whether the PIN is right. It never needs the PIN. So there is matches(pin) and no pin(). We keep a salted, slow hash instead of the PIN itself.
import hashlibimport hmacimport secretsclass PinGuard: MAX_TRIES = 3 def __init__(self, pin: str) -> None: if len(pin) != 4 or not (pin.isascii() and pin.isdigit()): raise ValueError("a PIN has four digits") self._salt = secrets.token_bytes(16) self._hash = self._mix(pin) self._tries = 0 def _mix(self, pin: str) -> bytes: return hashlib.pbkdf2_hmac("sha256", pin.encode(), self._salt, 100_000) def matches(self, pin: str) -> bool: if self._tries >= self.MAX_TRIES: return False ok = hmac.compare_digest(self._mix(pin), self._hash) self._tries = 0 if ok else self._tries + 1 return ok def __repr__(self) -> str: return "PinGuard(hidden)"g = PinGuard("4711")print(g, g.matches("0000"), g.matches("4711"))for _ in range(3): g.matches("0000")print("locked:", g.matches("4711") is False)compare_digest takes time that does not depend on where the first difference is. The Python documentation recommends it over == for this purpose. A four digit PIN has only 10,000 values, so the hash alone does not save it if the stored data is stolen. The try limit protects the online door. Real cash cards check PINs in hardware or with the bank.
The doors beside the getter
| Door | How it leaks | Close it |
|---|---|---|
toString, repr, record or dataclass defaults | a log line prints all fields | write your own, test it |
| Exceptions | the wrong PIN is quoted in the message | say: wrong PIN |
| Serialization to JSON | reflection reads private fields | explicit list of fields |
| Debug pages and memory dumps | everything is there | keep secrets short, limit who may dump |
| Timing | early exit tells how far it matched | constant time compare |
| Copies in strings | strings cannot be wiped | bytes or char arrays where wiping matters |
from dataclasses import dataclass, field@dataclassclass Leaky: name: str pin: str@dataclassclass Better: name: str pin: str = field(repr=False)print(Leaky("Sarah", "4711")) # this goes into a log fileprint(Better("Sarah", "4711")) # the value is still reachable, only not printedIs it a security border?
A common claim is: the field is private, so a hacker cannot change the balance. Be careful. private is checked by the compiler, and in Java also by the JVM, but reflection, native code, a debugger or a changed class file can get around it in the same process. In Python one dot is enough. Real protection is another process or machine, with authentication and rights: the bank's server, not the class.
Where do you put the rule “no withdrawal above the balance” for an online bank?
BreaksIn the app on the phone
- How
- The class is private and well written.
- Limit
- The phone belongs to the user. They can change the program.
- Choose when
- As a friendly hint only.
WorksIn the account class on the server
- How
- All requests pass the class.
- Limit
- A second program that writes the table goes around it. Two servers race.
- Choose when
- One program, one writer.
StrongClass on the server, plus a rule in the database
- How
- The class explains the refusal, a check constraint or a conditional update refuses as well.
- Limit
- The rule is written twice. Keep the second one tiny.
- Choose when
- Money, seats, stock.