Уяви наступний сценарій. Ти відправляєш зашифроване МРТ-зображення своєї голови на сервер AI-клініки. Сервер запускає нейромережу для виявлення пухлин. Нейромережа аналізує зображення, не розшифровуючи його жодної мілісекунди. Результат — теж зашифрований. Тільки ти, зі своїм приватним ключем, можеш прочитати діагноз.
Лікар ніколи не бачив твоє сканування. AI-система ніколи не бачила твоє сканування. Хакери, навіть якщо зламають сервер, отримають тільки зашифрований мусор. Але діагноз — точний, бо обчислення відбулися правильно.
Це не наукова фантастика з 2050 року. Це Homomorphic Encryption (HE) — криптографічна система, яка дозволяє виконувати обчислення на зашифрованих даних без їхнього розшифрування. Математично доведено. Практично реалізовано. Активно впроваджується.
Проблема: Privacy vs Utility — вічний конфлікт
Стандартна дилема cloud computing
Традиційний сценарій:
┌─────────────────────────────────────────────────────────┐
│ 1. У тебе є чутливі дані (медичні, фінансові) │
│ 2. Хочеш обробити їх потужним AI в cloud │
│ 3. Cloud provider бачить твої дані PLAIN TEXT │
│ 4. Trust? Security breach? Insider threat? │
└─────────────────────────────────────────────────────────┘
Поточні «рішення» та їхні недоліки:
| Підхід | Проблеми |
|--------|----------|
| Юридичні угоди (NDA, DPA) | Не захищають технічно, breach все одно можливий |
| On-premise processing | Дорого, немасштабовано, потрібна своя інфраструктура |
| Не використовувати cloud | Втрачаємо переваги масштабування, GPU clusters |
| Анонімізація | Часто reversible, втрачається utility |
| Довіра провайдеру | «Trust me, bro» — не криптографічна гарантія |
Гомоморфне шифрування: Математичний захист, який працює навіть якщо сервер зламаний, адміністратор корумпований, або провайдер отримав court order. Дані нечитаємі без приватного ключа, який ніколи не покидає клієнта.
Принцип гомоморфізму: магія математики
Звичайне шифрування
# Стандартне шифрування (AES, RSA)
ciphertext_a = Encrypt(key, plaintext_a) # E(5)
ciphertext_b = Encrypt(key, plaintext_b) # E(3)
# Операція на ciphertexts
result = ciphertext_a + ciphertext_b # Мусор!
# Щоб обчислити 5 + 3:
decrypted_a = Decrypt(key, ciphertext_a) # 5
decrypted_b = Decrypt(key, ciphertext_b) # 3
result = decrypted_a + decrypted_b # 8
encrypted_result = Encrypt(key, result) # E(8)
# Проблема: дані були розшифровані на сервері!
Гомоморфне шифрування
# Гомоморфне шифрування
ciphertext_a = HE_Encrypt(public_key, 5) # E(5)
ciphertext_b = HE_Encrypt(public_key, 3) # E(3)
# Гомоморфні операції — НА ЗАШИФРОВАНИХ даних
ciphertext_sum = HE_Add(ciphertext_a, ciphertext_b) # E(5+3) = E(8)
ciphertext_product = HE_Multiply(ciphertext_a, ciphertext_b) # E(5×3) = E(15)
# Розшифрування — тільки на клієнті
result_sum = HE_Decrypt(secret_key, ciphertext_sum) # 8
result_product = HE_Decrypt(secret_key, ciphertext_product) # 15
# Сервер НІКОЛИ не бачив 5, 3, 8, або 15!
# Сервер бачив тільки зашифрований мусор
Ключова властивість гомоморфізму:
E(a) ⊕ E(b) = E(a + b) # Гомоморфне додавання
E(a) ⊗ E(b) = E(a × b) # Гомоморфне множення
Де ⊕ і ⊗ — спеціальні операції на ciphertexts, які зберігають структуру операцій на plaintexts.
Типи гомоморфного шифрування
1. Partially Homomorphic Encryption (PHE)
Підтримує тільки одну операцію (або додавання, або множення), але необмежену кількість разів.
"""
PHE приклади — історичні схеми.
"""
class RSAMultiplicativelyHomomorphic:
"""
RSA — мультиплікативно гомоморфне (1977).
E(m1) × E(m2) = E(m1 × m2) mod n
"""
def __init__(self, bits: int = 2048):
self.p, self.q = self._generate_primes(bits // 2)
self.n = self.p * self.q
self.phi = (self.p - 1) * (self.q - 1)
self.e = 65537
self.d = self._mod_inverse(self.e, self.phi)
def encrypt(self, m: int) -> int:
"""E(m) = m^e mod n"""
return pow(m, self.e, self.n)
def decrypt(self, c: int) -> int:
"""D(c) = c^d mod n"""
return pow(c, self.d, self.n)
def homomorphic_multiply(self, c1: int, c2: int) -> int:
"""
E(m1) × E(m2) = m1^e × m2^e = (m1 × m2)^e = E(m1 × m2) mod n
"""
return (c1 * c2) % self.n
class PaillierAdditivelyHomomorphic:
"""
Paillier Cryptosystem (1999) — адитивно гомоморфне.
E(m1) × E(m2) = E(m1 + m2) mod n²
"""
def __init__(self, bits: int = 2048):
self.p, self.q = self._generate_safe_primes(bits // 2)
self.n = self.p * self.q
self.n_squared = self.n ** 2
self.g = self.n + 1 # Simplified generator
self.lambda_n = self._lcm(self.p - 1, self.q - 1)
self.mu = self._mod_inverse(self._L(pow(self.g, self.lambda_n, self.n_squared)), self.n)
def encrypt(self, m: int, r: int = None) -> int:
"""E(m) = g^m × r^n mod n²"""
if r is None:
r = self._random_coprime(self.n)
return (pow(self.g, m, self.n_squared) * pow(r, self.n, self.n_squared)) % self.n_squared
def decrypt(self, c: int) -> int:
"""D(c) = L(c^λ mod n²) × μ mod n"""
return (self._L(pow(c, self.lambda_n, self.n_squared)) * self.mu) % self.n
def homomorphic_add(self, c1: int, c2: int) -> int:
"""
E(m1) × E(m2) = g^(m1+m2) × r^n mod n² = E(m1 + m2)
"""
return (c1 * c2) % self.n_squared
def homomorphic_scalar_multiply(self, c: int, k: int) -> int:
"""
E(m)^k = E(k × m)
"""
return pow(c, k, self.n_squared)
def _L(self, u: int) -> int:
return (u - 1) // self.n
2. Somewhat Homomorphic Encryption (SHE)
Підтримує обидві операції, але обмежену кількість разів (особливо множень).
3. Fully Homomorphic Encryption (FHE)
Необмежена кількість додавань і множень — можна обчислити будь-яку функцію.
"""
FHE через LWE (Learning With Errors) — спрощена концепція.
"""
import numpy as np
from typing import Tuple
class LWEBasedFHE:
"""
Спрощена реалізація FHE на базі LWE.
Справжні бібліотеки (SEAL, OpenFHE) значно складніші.
"""
def __init__(self, n: int = 512, q: int = 2**32, sigma: float = 3.2):
"""
n: dimension of the lattice
q: modulus
sigma: standard deviation of error distribution
"""
self.n = n
self.q = q
self.sigma = sigma
def keygen(self) -> Tuple[np.ndarray, Tuple[np.ndarray, np.ndarray]]:
"""
Generate secret and public keys.
sk = s (secret vector)
pk = (A, b = A×s + e)
"""
# Secret key: small random vector
s = np.random.randint(-1, 2, self.n) # ternary secret
# Public key
m = self.n + 100 # number of samples
A = np.random.randint(0, self.q, (m, self.n))
# Error vector (Gaussian)
e = np.round(np.random.normal(0, self.sigma, m)).astype(int)
# b = A × s + e (mod q)
b = (A @ s + e) % self.q
secret_key = s
public_key = (A, b)
return secret_key, public_key
def encrypt(self, public_key: Tuple[np.ndarray, np.ndarray],
message: int) -> Tuple[np.ndarray, int]:
"""
Encrypt a single bit message ∈ {0, 1}.
"""
A, b = public_key
m = A.shape[0]
# Random subset selection (for CPA security)
r = np.random.randint(0, 2, m)
# c1 = Σ r_i × A_i
c1 = (r @ A) % self.q
# c2 = Σ r_i × b_i + message × (q/2)
c2 = (r @ b + message * (self.q // 2)) % self.q
return (c1, c2)
def decrypt(self, secret_key: np.ndarray,
ciphertext: Tuple[np.ndarray, int]) -> int:
"""
Decrypt ciphertext to recover message.
"""
c1, c2 = ciphertext
s = secret_key
# m ≈ c2 - c1 × s (mod q)
noise_result = (c2 - c1 @ s) % self.q
# Decode: check if closer to 0 or q/2
if noise_result > self.q // 4 and noise_result < 3 * self.q // 4:
return 1
else:
return 0
def homomorphic_add(self, ct1: Tuple[np.ndarray, int],
ct2: Tuple[np.ndarray, int]) -> Tuple[np.ndarray, int]:
"""
Add two ciphertexts: E(m1) + E(m2) = E(m1 + m2)
XOR for binary messages.
"""
c1_1, c2_1 = ct1
c1_2, c2_2 = ct2
c1_new = (c1_1 + c1_2) % self.q
c2_new = (c2_1 + c2_2) % self.q
return (c1_new, c2_new)
def homomorphic_multiply(self, ct1: Tuple[np.ndarray, int],
ct2: Tuple[np.ndarray, int],
relin_key) -> Tuple[np.ndarray, int]:
"""
Multiply two ciphertexts: E(m1) × E(m2) = E(m1 × m2)
AND for binary messages.
Проблема: розмір ciphertext росте, шум накопичується.
Потрібна relinearization та bootstrapping.
"""
# Спрощено — справжня реалізація набагато складніша
# Tensor product + relinearization
pass
class NoiseBudget:
"""
Шум накопичується з кожною операцією.
Bootstrapping "освіжує" ciphertext.
"""
def __init__(self, initial_budget: int = 100):
self.budget = initial_budget
def after_addition(self) -> int:
"""Додавання збільшує шум лінійно."""
self.budget -= 1
return self.budget
def after_multiplication(self) -> int:
"""Множення збільшує шум квадратично."""
self.budget -= 10
return self.budget
def bootstrap(self) -> int:
"""
Bootstrapping: гомоморфно виконуємо decryption circuit.
Це "освіжує" ciphertext, зменшуючи шум.
Дуже дороге: це bottleneck FHE продуктивності.
"""
self.budget = 100 # Reset
return self.budget
Сучасні FHE схеми та бібліотеки
CKKS: Approximate Arithmetic для ML
"""
CKKS (Cheon-Kim-Kim-Song) — FHE для наближених обчислень.
Ідеально для machine learning, де точність ±0.001 достатня.
"""
import tenseal as ts
import numpy as np
class CKKSDemo:
"""
TenSEAL — Python wrapper для Microsoft SEAL.
"""
def __init__(self, poly_modulus_degree: int = 8192,
coeff_mod_bit_sizes: list = [60, 40, 40, 60],
scale: float = 2**40):
"""
poly_modulus_degree: визначає security level та max multiplicative depth
coeff_mod_bit_sizes: ланцюг модулів для rescaling
scale: точність fixed-point представлення
"""
self.context = ts.context(
ts.SCHEME_TYPE.CKKS,
poly_modulus_degree=poly_modulus_degree,
coeff_mod_bit_sizes=coeff_mod_bit_sizes
)
self.context.generate_galois_keys()
self.context.global_scale = scale
def encrypt_vector(self, vector: list) -> ts.CKKSVector:
"""Шифруємо вектор чисел."""
return ts.ckks_vector(self.context, vector)
def decrypt_vector(self, encrypted: ts.CKKSVector) -> list:
"""Розшифровуємо вектор."""
return encrypted.decrypt()
def demo_linear_algebra(self):
"""
Демонстрація лінійної алгебри на зашифрованих даних.
"""
# Оригінальні дані
v1 = [1.0, 2.0, 3.0, 4.0]
v2 = [5.0, 6.0, 7.0, 8.0]
scalar = 2.5
# Шифруємо
enc_v1 = self.encrypt_vector(v1)
enc_v2 = self.encrypt_vector(v2)
# Операції НА ЗАШИФРОВАНИХ ДАНИХ
enc_sum = enc_v1 + enc_v2 # [6, 8, 10, 12]
enc_product = enc_v1 * enc_v2 # [5, 12, 21, 32]
enc_scaled = enc_v1 * scalar # [2.5, 5, 7.5, 10]
enc_dot = enc_v1.dot(enc_v2) # 70
# Розшифровуємо результати
results = {
"sum": self.decrypt_vector(enc_sum),
"elementwise_product": self.decrypt_vector(enc_product),
"scalar_multiply": self.decrypt_vector(enc_scaled),
"dot_product": self.decrypt_vector(enc_dot),
}
return results
def demo_polynomial_evaluation(self):
"""
Обчислення полінома на зашифрованих даних.
f(x) = 2x³ - 3x² + x - 5
"""
x = [1.0, 2.0, 3.0, 4.0]
enc_x = self.encrypt_vector(x)
# Обчислюємо поліном гомоморфно
enc_x2 = enc_x * enc_x # x²
enc_x3 = enc_x2 * enc_x # x³
# 2x³ - 3x² + x - 5
result = enc_x3 * 2 - enc_x2 * 3 + enc_x - 5
decrypted = self.decrypt_vector(result)
# Перевірка
expected = [2*xi**3 - 3*xi**2 + xi - 5 for xi in x]
return {
"encrypted_result": decrypted,
"expected": expected,
"max_error": max(abs(d - e) for d, e in zip(decrypted, expected))
}
class BFVDemo:
"""
BFV (Brakerski-Fan-Vercauteren) — FHE для точних обчислень.
Для integer arithmetic без втрати точності.
"""
def __init__(self, poly_modulus_degree: int = 4096,
plain_modulus: int = 786433):
self.context = ts.context(
ts.SCHEME_TYPE.BFV,
poly_modulus_degree=poly_modulus_degree,
plain_modulus=plain_modulus
)
def demo_integer_arithmetic(self):
"""Точна integer арифметика."""
v1 = [1, 2, 3, 4]
v2 = [5, 6, 7, 8]
enc_v1 = ts.bfv_vector(self.context, v1)
enc_v2 = ts.bfv_vector(self.context, v2)
# Точні цілочисельні операції
enc_sum = enc_v1 + enc_v2
enc_product = enc_v1 * enc_v2
return {
"sum": enc_sum.decrypt(), # [6, 8, 10, 12] — точно
"product": enc_product.decrypt() # [5, 12, 21, 32] — точно
}
OpenFHE: Найповніша бібліотека
"""
OpenFHE — найбільш повна open-source FHE бібліотека.
Підтримує: BFV, BGV, CKKS, TFHE, FHEW
"""
# pip install openfhe
from openfhe import *
class OpenFHEDemo:
"""Демонстрація OpenFHE."""
def setup_ckks(self):
"""Налаштування CKKS схеми."""
parameters = CCParamsCKKSRNS()
parameters.SetMultiplicativeDepth(5)
parameters.SetScalingModSize(50)
parameters.SetBatchSize(8)
cc = GenCryptoContext(parameters)
cc.Enable(PKESchemeFeature.PKE)
cc.Enable(PKESchemeFeature.KEYSWITCH)
cc.Enable(PKESchemeFeature.LEVELEDSHE)
keys = cc.KeyGen()
cc.EvalMultKeyGen(keys.secretKey)
cc.EvalRotateKeyGen(keys.secretKey, [1, 2, -1, -2])
return cc, keys
def demo_matrix_multiplication(self, cc, keys):
"""
Гомоморфне множення матриць.
Важливо для neural network inference.
"""
# Матриця як packed vector
matrix_a = [1.0, 2.0, 3.0, 4.0] # 2x2
vector_b = [5.0, 6.0]
pt_a = cc.MakeCKKSPackedPlaintext(matrix_a)
pt_b = cc.MakeCKKSPackedPlaintext(vector_b)
ct_a = cc.Encrypt(keys.publicKey, pt_a)
ct_b = cc.Encrypt(keys.publicKey, pt_b)
# Matrix-vector multiplication через rotations
# Це складніше, ніж просто додавання/множення
return ct_a, ct_b
FHE для Machine Learning: Private Inference
Архітектура Private ML Inference
┌─────────────────────────────────────────────────────────┐
│ CLIENT │
│ │
│ 1. Дані (медичне зображення) │
│ ↓ │
│ 2. Шифрування: E(дані) │
│ ↓ │
│ ═══════════════════════════════════════════════════ │
│ ↓ Тільки E(дані) по мережі │
└─────────────────────────────────────────────────────────┘
│
↓
┌─────────────────────────────────────────────────────────┐
│ SERVER │
│ │
│ 3. Отримує E(дані) — НЕ БАЧИТЬ оригінал │
│ ↓ │
│ 4. Neural Network на E(даних): │
│ - Linear layers: ✓ (матричні операції) │
│ - Convolutions: ✓ (складно, але можливо) │
│ - ReLU: ✗ → polynomial approximation │
│ - Softmax: ✗ → polynomial approximation │
│ ↓ │
│ 5. Результат: E(prediction) │
│ ↓ │
│ ═══════════════════════════════════════════════════ │
│ ↓ Тільки E(prediction) назад │
└─────────────────────────────────────────────────────────┘
│
↓
┌─────────────────────────────────────────────────────────┐
│ CLIENT │
│ │
│ 6. Розшифрування: D(E(prediction)) = prediction │
│ 7. Клієнт бачить результат │
│ │
│ Сервер НІКОЛИ не бачив ні дані, ні результат! │
└─────────────────────────────────────────────────────────┘
Реалізація Private Neural Network
"""
Private Neural Network Inference з TenSEAL.
"""
import tenseal as ts
import torch
import torch.nn as nn
import numpy as np
class PrivateNeuralNetwork:
"""
Neural network, що працює на зашифрованих даних.
"""
def __init__(self, plain_model: nn.Module, context: ts.Context):
"""
plain_model: натренована PyTorch модель
context: TenSEAL context для шифрування
"""
self.context = context
self.weights = self._extract_weights(plain_model)
def _extract_weights(self, model: nn.Module) -> dict:
"""Витягуємо ваги з PyTorch моделі."""
weights = {}
for name, param in model.named_parameters():
weights[name] = param.detach().numpy()
return weights
def encrypted_forward(self, enc_input: ts.CKKSVector) -> ts.CKKSVector:
"""
Forward pass на зашифрованому вході.
"""
# Layer 1: Linear
enc_output = self._encrypted_linear(
enc_input,
self.weights['fc1.weight'],
self.weights['fc1.bias']
)
# Activation: polynomial approximation of ReLU
enc_output = self._polynomial_activation(enc_output)
# Layer 2: Linear
enc_output = self._encrypted_linear(
enc_output,
self.weights['fc2.weight'],
self.weights['fc2.bias']
)
return enc_output
def _encrypted_linear(self, enc_x: ts.CKKSVector,
weight: np.ndarray,
bias: np.ndarray) -> ts.CKKSVector:
"""
Зашифрований linear layer: y = Wx + b
W та b — plaintext (модель не секретна в цьому сценарії)
x — encrypted
"""
# Matrix-vector multiplication
result = enc_x.mm(weight.tolist())
# Add bias
result = result + bias.tolist()
return result
def _polynomial_activation(self, enc_x: ts.CKKSVector,
degree: int = 3) -> ts.CKKSVector:
"""
ReLU неможливо обчислити гомоморфно (non-polynomial).
Апроксимуємо поліномом.
Популярні апроксимації:
- Square: f(x) = x²
- Smooth ReLU: f(x) ≈ 0.5x + 0.25x² для x ∈ [-1, 1]
- Higher degree polynomials
"""
# Square activation (простіше за ReLU)
return enc_x * enc_x
def _polynomial_relu_approx(self, enc_x: ts.CKKSVector) -> ts.CKKSVector:
"""
Polynomial approximation of ReLU.
ReLU(x) ≈ 0.5 + 0.197x + 0.5x² для x ∈ [-3, 3]
"""
enc_x2 = enc_x * enc_x
# 0.5 + 0.197x + 0.5x²
result = enc_x * 0.197
result = result + enc_x2 * 0.5
result = result + 0.5
return result
class HEFriendlyNetwork(nn.Module):
"""
Архітектура нейромережі, оптимізована для HE.
Особливості:
- Square activations замість ReLU
- Менша глибина (менше множень)
- BatchNorm замінено на LayerNorm або вилучено
- Average pooling замість Max pooling
"""
def __init__(self, input_size: int, hidden_size: int, output_size: int):
super().__init__()
self.fc1 = nn.Linear(input_size, hidden_size)
self.fc2 = nn.Linear(hidden_size, hidden_size)
self.fc3 = nn.Linear(hidden_size, output_size)
# Polynomial activation coefficients (learnable)
self.act_coeffs = nn.Parameter(torch.tensor([0.5, 0.197, 0.5]))
def forward(self, x):
x = self.fc1(x)
x = self._polynomial_activation(x)
x = self.fc2(x)
x = self._polynomial_activation(x)
x = self.fc3(x)
return x
def _polynomial_activation(self, x):
"""Polynomial activation: ax + bx² + c"""
return self.act_coeffs[0] * x + self.act_coeffs[1] * x**2 + self.act_coeffs[2]
class PrivateCNN:
"""
Encrypted Convolutional Neural Network.
"""
def __init__(self, context: ts.Context):
self.context = context
def encrypted_conv2d(self, enc_image: ts.CKKSVector,
kernel: np.ndarray,
stride: int = 1) -> ts.CKKSVector:
"""
Гомоморфна 2D convolution.
Дуже дорога операція:
- Потрібні rotations для sliding window
- Multiplicative depth росте
"""
# Image-to-column transformation
# Convolution = matrix multiplication після im2col
# Simplified: assume flattened representation
pass
def encrypted_average_pool(self, enc_input: ts.CKKSVector,
pool_size: int) -> ts.CKKSVector:
"""
Average pooling — HE-friendly (тільки додавання та множення на скаляр).
Max pooling — non-polynomial, потребує апроксимації.
"""
# Sum via rotations and add
pooled = enc_input
for i in range(1, pool_size):
rotated = enc_input # rotate by i positions
pooled = pooled + rotated
# Divide by pool_size
pooled = pooled * (1.0 / pool_size)
return pooled
Продуктивність: стан та прогрес
Бенчмарки Private Inference
| Method | Latency | Throughput | Accuracy | Memory |
|--------|---------|------------|----------|--------|
| Plaintext CNN | 10ms | 1000 img/s | 92.0% | 100MB |
| HE Naive | 30 min | 0.03 img/s | 92.0% | 50GB |
| HE Optimized (2023) | 30 sec | 2 img/s | 91.5% | 5GB |
| Hybrid HE+MPC | 5 sec | 12 img/s | 91.8% | 1GB |
| TFHE (Boolean) | 2 sec | 30 img/s | 90.0% | 500MB |
Прогрес FHE продуктивності
fhe_progress = {
2009: {"operation": "1 bit AND", "time": "30 minutes", "gentry_original": True},
2011: {"operation": "AES block", "time": "hours", "improvement": "10x"},
2015: {"operation": "AES block", "time": "minutes", "improvement": "100x"},
2018: {"operation": "Neural net layer", "time": "seconds", "improvement": "1000x"},
2021: {"operation": "ResNet inference", "time": "minutes", "improvement": "10000x"},
2024: {"operation": "Transformer layer", "time": "seconds", "improvement": "1000000x"},
}
# 1,000,000x improvement за 15 років!
# Подвоєння продуктивності кожні 18-24 місяці
Практичні Use Cases
1. Healthcare: Private Genomic Analysis
class PrivateGenomicAnalysis:
"""
Аналіз геномних даних без розкриття ДНК.
"""
def __init__(self, context: ts.Context):
self.context = context
def encrypted_gwas(self, enc_genotypes: list, enc_phenotypes: list):
"""
Genome-Wide Association Study на зашифрованих даних.
Пошук кореляцій між генетичними варіантами та хворобами
без розкриття індивідуальних геномів.
"""
# Chi-squared test approximation
# Logistic regression on encrypted data
pass
def private_ancestry(self, enc_snps: ts.CKKSVector):
"""
Визначення походження без розкриття генетичних даних.
"""
# Principal Component Analysis approximation
pass
2. Finance: Encrypted Credit Scoring
class PrivateCreditScoring:
"""
Кредитний скоринг без розкриття фінансових даних клієнта.
"""
def encrypted_logistic_regression(self, enc_features: ts.CKKSVector,
model_weights: np.ndarray,
model_bias: float):
"""
Логістична регресія на зашифрованих даних.
Bank бачить тільки APPROVE/REJECT.
Не бачить income, debt, history клієнта.
"""
# Linear combination
enc_logit = enc_features.dot(model_weights.tolist()) + model_bias
# Sigmoid approximation (polynomial)
# σ(x) ≈ 0.5 + 0.197x - 0.004x³ для x ∈ [-5, 5]
enc_score = self._polynomial_sigmoid(enc_logit)
return enc_score
def _polynomial_sigmoid(self, enc_x: ts.CKKSVector) -> ts.CKKSVector:
"""Polynomial approximation of sigmoid."""
enc_x3 = enc_x * enc_x * enc_x
return enc_x * 0.197 - enc_x3 * 0.004 + 0.5
3. Cloud ML: Private Model Inference
class PrivateMLaaS:
"""
Machine Learning as a Service з privacy.
Клієнт: отримує prediction без розкриття даних
Провайдер: захищає модель (IP)
"""
def __init__(self, model_weights: dict):
self.weights = model_weights # Server's secret model
def private_inference(self, client_context: ts.Context,
enc_input: ts.CKKSVector) -> ts.CKKSVector:
"""
Server виконує inference на даних клієнта.
Клієнт не бачить weights моделі.
Server не бачить input та output клієнта.
"""
# Hybrid approach:
# - Model weights encrypted with server's key
# - Input encrypted with client's key
# - Requires multi-key HE or interactive protocol
pass
Ідеї для дослідження
Для бакалавра:
- Базові HE операції з TenSEAL на прикладах
- Encrypted linear regression
- Benchmark: Paillier vs CKKS для додавання
- Private voting system implementation
Для магістра:
- Private neural network inference (MNIST, CIFAR)
- HE-friendly model architectures
- Hybrid HE + Secure Multi-Party Computation
- Comparison: CKKS vs BFV vs TFHE
Для PhD:
- Novel bootstrapping algorithms (швидший FHE)
- HE для transformers та LLM
- Hardware acceleration для HE (GPU, FPGA, ASIC)
- Quantum-resistant HE schemes
Висновок: privacy без компромісів
Cloud computing дає нам зручність, масштабування, економію. Але традиційно вимагає довіри провайдеру з нашими даними. Гомоморфне шифрування ламає цю дилему назавжди.
Ти отримуєш переваги cloud computing — без privacy trade-off. Не «ми обіцяємо не дивитися», а математична гарантія, яку неможливо обійти без приватного ключа.
Повільно? Так, поки що в 100-1000x порівняно з plaintext. Але прогрес експоненційний: мільйон разів швидше за 15 років. Через 5-10 років FHE буде практичним для багатьох real-world applications.
Хто розуміє FHE сьогодні — буде будувати privacy-preserving інфраструктуру майбутнього. Якщо вас цікавить ця тема для академічної роботи, експерти SKP-Degree на skp-degree.com.ua допоможуть з реалізацією гомоморфних систем та private ML. Консультації доступні в Telegram: @kursovi_diplomy.
Гомоморфне шифрування, FHE, CKKS, BFV, TenSEAL, Microsoft SEAL, private machine learning, secure computation, криптографія — ключові терміни для дипломної, магістерської чи PhD роботи з приватності даних та безпечних обчислень.