Skip to content
Book 1: Theory Fundamentals

Book 1 · Chapter 6

Security, privacy and data integrity

§6.1§6.2Core · ≈ 10.2 m · ↗B1·6

This chapter is in the ebook.

Read it in full on cswithzak.com. Every question has its mark scheme and every program is ready to run. The free practice for each section is below, with the short code the book prints beside it.

Open in the ebook

For the whole chapter

§6.1 Data security

Short code B1·6·1

§6.2 Data integrity

Short code B1·6·2

Security, privacy and integrity

Short code B1·6·10

Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.

Protecting the data and the system

Short code B1·6·11

Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.

Malware

Short code B1·6·12

Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.

Phishing and pharming

Short code B1·6·13

Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.

Who are you? Accounts, passwords and authentication

Short code B1·6·14

Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.

Firewalls, anti-virus and anti-spyware

Short code B1·6·15

Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.

Encryption and digital signatures

Short code B1·6·16

def xor_cipher(data, key):
    out = []
    for i, b in enumerate(data):
        out.append(b ^ key[i % len(key)])
    return bytes(out)

message = b"Order 1182: 3 copies"
cipher = xor_cipher(message, b"k3y")
print(cipher.hex()[:24], "...")
print(xor_cipher(cipher, b"k3y").decode())
print(xor_cipher(cipher, b"kEy").hex()[:24], "...")
A toy cipher, only to show the idea: each byte of the plaintext is combined with a key using XOR. With the right key the ciphertext turns back into the message; with the wrong key it stays meaningless. (Real encryption uses far stronger algorithms.)

Output

24411d0e41595a0241590959 ...
Order 1182: 3 copies
4f0464650420314738324c20 ...
Run and checked before printing
import hashlib
docs = ("Pay Lin 300 for March.",
        "Pay Lin 900 for March.")
for doc in docs:
    h = hashlib.sha256(doc.encode()).hexdigest()
    print(h[:16], doc)
A hash is a short fixed-length value calculated from a document. Change one character and the hash is completely different. Digital signatures rely on this (the first 16 hexadecimal digits of each SHA-256 hash are shown).

Output

cd06020ab28af497 Pay Lin 300 for March.
ca245ef292366b09 Pay Lin 900 for March.
Run and checked before printing

Backup, physical security and answering threat questions

Short code B1·6·17

Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.

Data integrity: validation and verification

Short code B1·6·18

Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.

Validation checks

Short code B1·6·19

DECLARE Quantity : INTEGER
REPEAT
   OUTPUT "Quantity (1 to 20): "
   INPUT Quantity
   IF Quantity < 1 OR Quantity > 20 THEN
      OUTPUT "Rejected: ", Quantity
   ENDIF
UNTIL Quantity >= 1 AND Quantity <= 20
OUTPUT "Accepted: ", Quantity
A range check on the quantity typed on an order screen. The REPEAT loop keeps asking until the value is between 1 and 20 inclusive. Here the user types 0, then 25, then 4.

Output

Quantity (1 to 20):
› 0
Rejected: 0
Quantity (1 to 20):
› 25
Rejected: 25
Quantity (1 to 20):
› 4
Accepted: 4
Run and checked before printing
DECLARE Age : INTEGER
INPUT Age
IF Age < 13 THEN
   OUTPUT "Rejected: too young for an account"
ELSE
   OUTPUT "Accepted"
ENDIF
A limit check tests one boundary only: a loyalty account holder must be at least 13. There is no upper limit to check.

Output

› 12
Rejected: too young for an account
Run and checked before printing
DECLARE Postcode : STRING
INPUT Postcode
IF Postcode = "" THEN
   OUTPUT "Rejected: nothing entered"
ELSE
   IF LENGTH(Postcode) < 5 THEN
      OUTPUT "Rejected: too short"
   ELSE
      IF LENGTH(Postcode) > 8 THEN
         OUTPUT "Rejected: too long"
      ELSE
         OUTPUT "Accepted"
      ENDIF
   ENDIF
ENDIF
A presence check, then a length check, on a delivery postcode. The presence check must come first: an empty string would also fail the length check, but with the wrong message.

Output

› SW1A1AAX9
Rejected: too long
Run and checked before printing
FUNCTION IsCard(Card : STRING) RETURNS BOOLEAN
   DECLARE Index : INTEGER
   DECLARE Ch : STRING
   DECLARE Valid : BOOLEAN
   Valid ← LENGTH(Card) = 6
   IF Valid THEN
      FOR Index ← 1 TO 6
         Ch ← MID(Card, Index, 1)
         IF Index <= 2 THEN
            IF Ch < "A" OR Ch > "Z" THEN
               Valid ← FALSE
            ENDIF
         ELSE
            IF Ch < "0" OR Ch > "9" THEN
               Valid ← FALSE
            ENDIF
         ENDIF
      NEXT Index
   ENDIF
   RETURN Valid
ENDFUNCTION

OUTPUT "LC2041 ", IsCard("LC2041")
OUTPUT "LC20A1 ", IsCard("LC20A1")
OUTPUT "L20415 ", IsCard("L20415")
OUTPUT "LC204 ", IsCard("LC204")
A format check on loyalty card numbers: two capital letters, then four digits (pattern LLDDDD). The function checks the length first, then each character against the type it must be.

Output

LC2041 TRUE
LC20A1 FALSE
L20415 FALSE
LC204 FALSE
Run and checked before printing
DECLARE Genres : ARRAY[1:5] OF STRING
DECLARE Code : STRING
DECLARE Index : INTEGER
DECLARE Found : BOOLEAN
Genres[1] ← "FIC"
Genres[2] ← "BIO"
Genres[3] ← "SCI"
Genres[4] ← "KID"
Genres[5] ← "TRV"
INPUT Code
Found ← FALSE
Index ← 1
WHILE Index <= 5 AND NOT Found
   IF Genres[Index] = Code THEN
      Found ← TRUE
   ENDIF
   Index ← Index + 1
ENDWHILE
IF Found THEN
   OUTPUT "Accepted: ", Code
ELSE
   OUTPUT "Rejected: ", Code
ENDIF
An existence (lookup) check: the genre code typed must be one of the codes the shop really uses. The loop stops as soon as a match is found.

Output

› SFI
Rejected: SFI
Run and checked before printing

Check digits

Short code B1·6·20

DECLARE Number : INTEGER
DECLARE Weight : INTEGER
DECLARE Total : INTEGER
DECLARE CheckDigit : INTEGER
Number ← 4719
Weight ← 2
Total ← 0
WHILE Number > 0
   Total ← Total + (Number MOD 10) * Weight
   Number ← Number DIV 10
   Weight ← Weight + 1
ENDWHILE
CheckDigit ← 11 - (Total MOD 11)
IF CheckDigit = 11 THEN
   CheckDigit ← 0
ENDIF
OUTPUT "Total ", Total
OUTPUT "Remainder ", Total MOD 11
OUTPUT "Check digit ", CheckDigit
Making a modulo-11 check digit for customer number 4719. MOD 10 takes the rightmost digit and DIV 10 drops it, so the weights start at 2 on the right and go up by one.

Output

Total 69
Remainder 3
Check digit 8
Run and checked before printing
FUNCTION CheckOK(Number : INTEGER) RETURNS BOOLEAN
   DECLARE Weight : INTEGER
   DECLARE Total : INTEGER
   Weight ← 1
   Total ← 0
   WHILE Number > 0
      Total ← Total + (Number MOD 10) * Weight
      Number ← Number DIV 10
      Weight ← Weight + 1
   ENDWHILE
   RETURN Total MOD 11 = 0
ENDFUNCTION

OUTPUT "47198 ", CheckOK(47198)
OUTPUT "47918 ", CheckOK(47918)
OUTPUT "47199 ", CheckOK(47199)
Checking a whole number, check digit included. The check digit gets weight 1, and a correct number gives a total that divides exactly by 11. Swapping two digits (47198 → 47918) is caught.

Output

47198 TRUE
47918 FALSE
47199 FALSE
Run and checked before printing
def weighted(digits):   # weights 1, 3, 1, 3 ...
    total = 0
    for i, d in enumerate(digits):
        total += int(d) * (1 if i % 2 == 0 else 3)
    return total

t = weighted("978190750283")
print("sum", t, "check digit", (10 - t % 10) % 10)
for isbn in ("9781907502835", "9781907502635"):
    print(isbn, weighted(isbn) % 10 == 0)
The ISBN-13 on a book's barcode uses a different check digit rule: weights 1, 3, 1, 3… and MOD 10. Here is the check digit for an invented ISBN, and a check of one digit mistyped.

Output

sum 95 check digit 5
9781907502835 True
9781907502635 False
Run and checked before printing

Verification during data entry

Short code B1·6·21

DECLARE First : STRING
DECLARE Second : STRING
OUTPUT "Email: "
INPUT First
OUTPUT "Email again: "
INPUT Second
IF First = Second THEN
   OUTPUT "Verified"
ELSE
   OUTPUT "Different: type it again"
ENDIF
Double entry: the new member types the email address twice and the two copies are compared. A typing slip in one copy is caught. (If both copies carry the same slip, it is not.)

Output

Email:
› mina@inkwell.example
Email again:
› mina@inkwel.example
Different: type it again
Run and checked before printing

Parity checks

Short code B1·6·22

for ch in "INK7":
    bits = format(ord(ch), "07b")   # 7-bit ASCII
    n = bits.count("1")
    even = "0" if n % 2 == 0 else "1"
    odd = "1" if even == "0" else "0"
    print(ch, bits, n, even + bits, odd + bits)
Parity bits for the warehouse stock code INK7. Each character is 7-bit ASCII; the parity bit goes in front. Count the 1s, then choose the bit that makes the total even (or odd). Each line shows the character, its 7-bit code, the number of 1s, then the byte sent under even parity and under odd parity.

Output

I 1001001 3 11001001 01001001
N 1001110 4 01001110 11001110
K 1001011 4 01001011 11001011
7 0110111 5 10110111 00110111
Run and checked before printing
sent = "01001011"   # K, even parity bit first
got = "01111011"    # two bits flipped
for byte in (sent, got):
    n = byte.count("1")
    print(byte, "ones:", n, "passes:", n % 2 == 0)
Why parity is not enough on its own: two bits of K flip in transit. The count of 1s changes by two, so it is still even and the byte passes the check.

Output

01001011 ones: 4 passes: True
01111011 ones: 6 passes: True
Run and checked before printing

Parity blocks: finding the bad bit

Short code B1·6·23

# I N K 7, even parity bit first
rows = ["11001001", "01001110",
        "01001011", "10110111"]

def odd_count(bits):
    return bits.count("1") % 2 == 1

def column(block, c):
    return "".join(r[c] for r in block)

pb = ""
for c in range(8):
    bad = odd_count(column(rows, c))
    pb += "1" if bad else "0"
print("parity byte:", pb)

got = rows[:]
got[2] = "01011011"    # row 3, bit 4 flipped
bad_r = [i + 1 for i in range(4)
         if odd_count(got[i])]
bad_c = [c + 1 for c in range(8)
         if odd_count(column(got, c) + pb[c])]
print("failing row:", bad_r, "column:", bad_c)
r, c = bad_r[0] - 1, bad_c[0] - 1
flip = "1" if got[r][c] == "0" else "0"
print("corrected:",
      got[r][:c] + flip + got[r][c + 1:])
A parity block for INK7 under even parity. The parity byte is worked out column by column, exactly as each row's parity bit was worked out along the row. Then one bit is flipped on the way: one row and one column fail, and where they cross is the bad bit.

Output

parity byte: 01111011
failing row: [3] column: [4]
corrected: 01001011
Run and checked before printing

Checksums, and choosing a method

Short code B1·6·24

def checksum(data):
    return sum(data) % 256

packet = [120, 45, 200, 77]
sent = checksum(packet)
print("sum", sum(packet), "-> checksum", sent)

arrived = [120, 47, 200, 77]   # 45 became 47
mine = checksum(arrived)
print("receiver:", mine, "matches:", mine == sent)
A checksum on one packet of the warehouse's stock update. The sender adds the four bytes and keeps the total MOD 256, so it fits in one byte. The receiver repeats the sum: a single changed byte gives a different checksum, so the packet is sent again.

Output

sum 442 -> checksum 186
receiver: 188 matches: False
Run and checked before printing
packet = [120, 45, 200, 77]
swapped = [45, 120, 200, 77]
print(sum(packet) % 256, sum(swapped) % 256)
A simple additive checksum cannot see the order of the bytes: swap two of them and the sum is unchanged. Real protocols use cleverer checksums for this reason.

Output

186 186
Run and checked before printing

Workbook 1: Security, privacy and data integrity

Short code W1·6 · Theory Fundamentals Workbook

The write-in workbook for this chapter has drills, exam-style practice, trace tables, fix-the-mistake and mark-it-yourself pages. Its full mark schemes and an interactive version arrive here with the chapter.

Ask Z about Security, privacy and data integrity
Buy ZAK's books — WhatsApp the books desk: Buy the booksPrint or ebook