|
| 1 | +"""FF1 Format-Preserving Encryption (NIST SP 800-38G).""" |
| 2 | + |
| 3 | +from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes |
| 4 | +import math |
| 5 | + |
| 6 | +DIGITS = "0123456789" |
| 7 | +ALPHANUMERIC = "0123456789abcdefghijklmnopqrstuvwxyz" |
| 8 | + |
| 9 | + |
| 10 | +class FF1: |
| 11 | + def __init__(self, key: bytes, tweak: bytes, alphabet: str = ALPHANUMERIC): |
| 12 | + if len(key) not in (16, 24, 32): |
| 13 | + raise ValueError(f"Key must be 16, 24, or 32 bytes, got {len(key)}") |
| 14 | + if len(alphabet) < 2: |
| 15 | + raise ValueError("Alphabet must have >= 2 characters") |
| 16 | + self._key = key |
| 17 | + self._tweak = tweak |
| 18 | + self._alphabet = alphabet |
| 19 | + self._radix = len(alphabet) |
| 20 | + self._char_to_int = {c: i for i, c in enumerate(alphabet)} |
| 21 | + |
| 22 | + def encrypt(self, plaintext: str) -> str: |
| 23 | + digits = self._to_digits(plaintext) |
| 24 | + result = self._ff1_encrypt(digits, self._tweak) |
| 25 | + return self._from_digits(result) |
| 26 | + |
| 27 | + def decrypt(self, ciphertext: str) -> str: |
| 28 | + digits = self._to_digits(ciphertext) |
| 29 | + result = self._ff1_decrypt(digits, self._tweak) |
| 30 | + return self._from_digits(result) |
| 31 | + |
| 32 | + def _to_digits(self, s: str) -> list[int]: |
| 33 | + return [self._char_to_int[c] for c in s] |
| 34 | + |
| 35 | + def _from_digits(self, d: list[int]) -> str: |
| 36 | + return "".join(self._alphabet[i] for i in d) |
| 37 | + |
| 38 | + def _aes_ecb(self, block: bytes) -> bytes: |
| 39 | + cipher = Cipher(algorithms.AES(self._key), modes.ECB()) |
| 40 | + enc = cipher.encryptor() |
| 41 | + return enc.update(block) + enc.finalize() |
| 42 | + |
| 43 | + def _prf(self, data: bytes) -> bytes: |
| 44 | + y = b"\x00" * 16 |
| 45 | + for i in range(0, len(data), 16): |
| 46 | + block = bytes(a ^ b for a, b in zip(y, data[i : i + 16])) |
| 47 | + y = self._aes_ecb(block) |
| 48 | + return y |
| 49 | + |
| 50 | + def _expand_s(self, r: bytes, d: int) -> bytes: |
| 51 | + blocks = (d + 15) // 16 |
| 52 | + out = bytearray(r) |
| 53 | + prev = r |
| 54 | + for j in range(1, blocks): |
| 55 | + x = j.to_bytes(16, "big") |
| 56 | + x = bytes(a ^ b for a, b in zip(x, prev)) |
| 57 | + enc = self._aes_ecb(x) |
| 58 | + out.extend(enc) |
| 59 | + prev = enc |
| 60 | + return bytes(out[:d]) |
| 61 | + |
| 62 | + def _num(self, digits: list[int]) -> int: |
| 63 | + result = 0 |
| 64 | + for d in digits: |
| 65 | + result = result * self._radix + d |
| 66 | + return result |
| 67 | + |
| 68 | + def _str(self, num: int, length: int) -> list[int]: |
| 69 | + result = [0] * length |
| 70 | + for i in range(length - 1, -1, -1): |
| 71 | + result[i] = num % self._radix |
| 72 | + num //= self._radix |
| 73 | + return result |
| 74 | + |
| 75 | + def _compute_b(self, v: int) -> int: |
| 76 | + return math.ceil(math.ceil(v * math.log2(self._radix)) / 8) |
| 77 | + |
| 78 | + def _build_p(self, u: int, n: int, t: int) -> bytes: |
| 79 | + return bytes( |
| 80 | + [1, 2, 1, (self._radix >> 16) & 0xFF, (self._radix >> 8) & 0xFF, self._radix & 0xFF, 10, u] |
| 81 | + + list(n.to_bytes(4, "big")) |
| 82 | + + list(t.to_bytes(4, "big")) |
| 83 | + ) |
| 84 | + |
| 85 | + def _build_q(self, T: bytes, i: int, num_bytes: bytes, b: int) -> bytes: |
| 86 | + pad = (16 - ((len(T) + 1 + b) % 16)) % 16 |
| 87 | + q = bytearray(T) |
| 88 | + q.extend(b"\x00" * pad) |
| 89 | + q.append(i) |
| 90 | + if len(num_bytes) < b: |
| 91 | + q.extend(b"\x00" * (b - len(num_bytes))) |
| 92 | + start = max(0, len(num_bytes) - b) |
| 93 | + q.extend(num_bytes[start:]) |
| 94 | + return bytes(q) |
| 95 | + |
| 96 | + def _ff1_encrypt(self, pt: list[int], T: bytes) -> list[int]: |
| 97 | + n = len(pt) |
| 98 | + u, v = n // 2, n - n // 2 |
| 99 | + A, B = pt[:u], pt[u:] |
| 100 | + |
| 101 | + b = self._compute_b(v) |
| 102 | + d = 4 * ((b + 3) // 4) + 4 |
| 103 | + P = self._build_p(u, n, len(T)) |
| 104 | + |
| 105 | + for i in range(10): |
| 106 | + num_b = self._num(B).to_bytes(max(b, 1), "big") |
| 107 | + if len(num_b) > b: |
| 108 | + num_b = num_b[-b:] if b > 0 else b"" |
| 109 | + Q = self._build_q(T, i, num_b, b) |
| 110 | + R = self._prf(P + Q) |
| 111 | + S = self._expand_s(R, d) |
| 112 | + y = int.from_bytes(S, "big") |
| 113 | + |
| 114 | + m = u if i % 2 == 0 else v |
| 115 | + c = (self._num(A) + y) % (self._radix ** m) |
| 116 | + A, B = B, self._str(c, m) |
| 117 | + |
| 118 | + return A + B |
| 119 | + |
| 120 | + def _ff1_decrypt(self, ct: list[int], T: bytes) -> list[int]: |
| 121 | + n = len(ct) |
| 122 | + u, v = n // 2, n - n // 2 |
| 123 | + A, B = ct[:u], ct[u:] |
| 124 | + |
| 125 | + b = self._compute_b(v) |
| 126 | + d = 4 * ((b + 3) // 4) + 4 |
| 127 | + P = self._build_p(u, n, len(T)) |
| 128 | + |
| 129 | + for i in range(9, -1, -1): |
| 130 | + num_a = self._num(A).to_bytes(max(b, 1), "big") |
| 131 | + if len(num_a) > b: |
| 132 | + num_a = num_a[-b:] if b > 0 else b"" |
| 133 | + Q = self._build_q(T, i, num_a, b) |
| 134 | + R = self._prf(P + Q) |
| 135 | + S = self._expand_s(R, d) |
| 136 | + y = int.from_bytes(S, "big") |
| 137 | + |
| 138 | + m = u if i % 2 == 0 else v |
| 139 | + mod = self._radix ** m |
| 140 | + c = (self._num(B) - y) % mod |
| 141 | + B, A = A, self._str(c, m) |
| 142 | + |
| 143 | + return A + B |
0 commit comments