[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
@@ -1,63 +1,284 @@
---
id: wiki-2026-0508-homomorphic-encryption
title: Homomorphic Encryption
title: Homomorphic Encryption (HE)
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [SEC-HOMO-001]
aliases: [HE, FHE, homomorphic encryption, fully homomorphic, CKKS, BFV, BGV, TFHE, privacy-preserving ML]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [security, cryptography, homomorphic-encryption, Privacy-Preserving-AI, data-privacy]
confidence_score: 0.93
verification_status: applied
tags: [cryptography, fhe, privacy, encryption, ml-privacy, secure-computation]
raw_sources: []
last_reinforced: 2026-04-26
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: C++ / Python
framework: Microsoft SEAL / OpenFHE / Concrete / TFHE-rs
---
# Homomorphic Encryption (동형 암호)
# Homomorphic Encryption
## 📌 한 줄 통찰 (The Karpathy Summary)
> "데이터의 자물쇠를 풀지 않고도 그 내용물을 가공하여, 결과물만을 안전하게 돌려받아라" — 암호화된 데이터를 복호화하지 않은 상태에서 덧셈, 곱셈 등 수학적 연산을 수행하고 그 결과 또한 암호화된 형태로 얻을 수 있게 하는 혁신적인 암호 체계.
## 한 줄
> **"매 encrypted data 의 의 의 직접 의 compute"**. 매 plaintext 의 reveal X. 매 Gentry 2009 (FHE breakthrough). 매 modern: 매 CKKS (real / approximate), BFV/BGV (integer), TFHE (Boolean). 매 응용: 매 privacy-preserving ML, 매 cloud, 매 medical.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Privacy-Preserving Computing" — 민감한 원본 데이터(의료 정보, 개인 금융 등)를 외부에 공개하지 않고도 클라우드나 AI 모델이 이를 학습하거나 분석할 수 있게 하는 보안 연산 패턴.
- **주요 유형:**
- **Partially Homomorphic (PHE):** 덧셈이나 곱셈 중 한 종류의 연산만 지원 (예: RSA, Paillier).
- **Somewhat Homomorphic (SHE):** 제한된 횟수의 연산 지원.
- **Fully Homomorphic (FHE):** 횟수 제한 없이 모든 종류의 산술 연산 지원 (가장 강력함).
- **의의:** '데이터 활용'과 '개인정보 보호'라는 상충하는 가치를 동시에 만족시킬 수 있어, 미래 지능형 의료, 보안 클라우드, 분산 AI 학습의 핵심 기술로 평가됨.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 연산 속도가 너무 느려 실질적 사용이 불가능하다는 인식이 강했으나, 최근 알고리즘 최적화와 가속 하드웨어의 발전으로 실무 적용 가능한 영역(통계 분석 등)이 확대되고 있음.
- **정책 변화:** Antigravity 프로젝트는 사용자의 민감한 개인 정보를 포함한 '로컬 브레인 로그'를 분석할 때, 동형 암호 기술을 적용하여 분석 서버가 원본 텍스트를 절대 볼 수 없도록 하는 보안 표준을 연구 중임.
### 매 levels
- **Partial HE** (PHE): 매 single op (add or mul).
- **Somewhat HE** (SHE): 매 limited depth.
- **Leveled HE**: 매 known depth.
- **Fully HE** (FHE): 매 unlimited depth via bootstrapping.
## 🔗 지식 연결 (Graph)
- Data-Privacy-Foundations, [[Federated-Learning|Federated-Learning]], Differential-Privacy, Cloud-Security-[[Mastery|Mastery]]
- **Raw Source:** 10_Wiki/Topics/AI/Homomorphic-Encryption.md
### 매 schemes
- **CKKS**: 매 approximate arithmetic on real / complex (modern ML).
- **BFV / BGV**: 매 exact integer.
- **TFHE**: 매 fast bootstrapping, Boolean.
- **NTRU**, **GSW**: 매 historical / specialized.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 modern library
- **Microsoft SEAL** (CKKS, BFV).
- **OpenFHE** (모든 schemes).
- **Concrete** (Zama, TFHE).
- **TFHE-rs** (Rust).
- **PySEAL**, **TenSEAL** (Python).
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 응용
1. **Privacy-preserving ML inference**.
2. **Medical** (encrypted genomic).
3. **Financial** (encrypted query).
4. **Cloud compute** (zero-knowledge).
5. **Federated learning** + HE.
6. **Smart contract** (FHEVM).
**언제 쓰면 안 되는가:**
- *(TODO)*
### 매 cost
- 매 100x-10000x slowdown vs plaintext.
- 매 modern hardware (GPU FHE) 의 의 의 reduce.
- 매 ciphertext 매 100-1000x larger.
## 🧪 검증 상태 (Validation)
## 💻 패턴
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### TenSEAL (CKKS, Python)
```python
import tenseal as ts
## 🧬 중복 검사 (Duplicate Check)
context = ts.context(ts.SCHEME_TYPE.CKKS, poly_modulus_degree=8192,
coeff_mod_bit_sizes=[60, 40, 40, 60])
context.global_scale = 2**40
context.generate_galois_keys()
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
# 매 encrypt
v1 = ts.ckks_vector(context, [1.0, 2.0, 3.0])
v2 = ts.ckks_vector(context, [4.0, 5.0, 6.0])
## 🕓 변경 이력 (Changelog)
# 매 compute on ciphertext
add = v1 + v2 # 매 [5, 7, 9]
mul = v1 * v2 # 매 [4, 10, 18]
dot = v1.dot(v2) # 매 32
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
# 매 decrypt only when needed
print(add.decrypt())
```
### Microsoft SEAL (BFV, C++)
```cpp
#include "seal/seal.h"
using namespace seal;
EncryptionParameters parms(scheme_type::bfv);
parms.set_poly_modulus_degree(4096);
parms.set_coeff_modulus(CoeffModulus::BFVDefault(4096));
parms.set_plain_modulus(1024);
SEALContext context(parms);
KeyGenerator keygen(context);
PublicKey public_key; keygen.create_public_key(public_key);
SecretKey secret_key = keygen.secret_key();
Encryptor encryptor(context, public_key);
Evaluator evaluator(context);
Decryptor decryptor(context, secret_key);
Plaintext x_plain("5"); Ciphertext x_encrypted;
encryptor.encrypt(x_plain, x_encrypted);
Ciphertext result;
evaluator.square(x_encrypted, result); // 매 5² = 25 (encrypted)
```
### Encrypted ML inference (logistic regression)
```python
def encrypted_logistic_regression(encrypted_x, weights_plaintext, bias_plaintext):
"""매 매 매 weights / bias 매 plaintext, 매 input 매 encrypted."""
z = encrypted_x.dot(weights_plaintext) + bias_plaintext
# 매 sigmoid approximation (poly degree 3)
z2 = z * z
z3 = z2 * z
sigmoid_approx = 0.5 + 0.197 * z - 0.004 * z3 # 매 around 0
return sigmoid_approx
```
### Sigmoid polynomial approx (CKKS)
```python
def sigmoid_poly_approx(z):
"""매 매 [-5, 5] 의 의 의 valid."""
# 매 deg 3 Taylor-like
z2 = z * z
z3 = z2 * z
z5 = z3 * z2
return 0.5 + 0.197 * z - 0.004 * z3 + 0.0001 * z5
```
### Encrypted neural net (CKKS)
```python
def encrypted_dense_layer(enc_x, weights, bias):
"""매 매 layer 의 linear part 는 가능, 매 ReLU 는 polynomial approx."""
z = enc_x.mm(weights) + bias # 매 matrix-vector
return polynomial_relu_approx(z)
def polynomial_relu_approx(z):
"""매 ReLU(x) ≈ a + b*x + c*x²."""
z2 = z * z
return 0.375 * z + 0.5 + 0.125 * z2 # 매 매 small range
```
### Bootstrapping (FHE refresh)
```python
# 매 SEAL CKKS 의 native bootstrap
# 매 OpenFHE
import openfhe
parameters = openfhe.CCParamsCKKSRNS()
parameters.SetMultiplicativeDepth(20)
cc = openfhe.GenCryptoContext(parameters)
cc.Enable(openfhe.PKESchemeFeature.PKE)
cc.Enable(openfhe.PKESchemeFeature.LEVELEDSHE)
cc.Enable(openfhe.PKESchemeFeature.ADVANCEDSHE)
cc.Enable(openfhe.PKESchemeFeature.FHE)
# 매 bootstrap
ct_refreshed = cc.EvalBootstrap(ct)
```
### TFHE (Boolean fast)
```rust
use tfhe::boolean::prelude::*;
let (client_key, server_key) = gen_keys();
let ct1 = client_key.encrypt(true);
let ct2 = client_key.encrypt(false);
// 매 server side
let result = server_key.and(&ct1, &ct2);
// 매 client side
let dec = client_key.decrypt(&result); // 매 false
```
### Concrete-ML (Zama)
```python
from concrete.ml.sklearn import LogisticRegression
model = LogisticRegression(n_bits=8)
model.fit(X_train, y_train)
# 매 compile to FHE
model.compile(X_train)
# 매 encrypted inference
y_pred = model.predict(X_test_encrypted)
```
### Multi-party (HE + secret share)
```python
def hybrid_compute(encrypted_data_party_a, encrypted_data_party_b, secure_aggregator):
# 매 매 party 매 encrypt own data
# 매 aggregator 의 의 의 sum (HE)
sum_encrypted = encrypted_data_party_a + encrypted_data_party_b
# 매 only authorized 매 decrypt
return sum_encrypted
```
### Performance benchmark
```python
import time
def benchmark_he(scheme='ckks'):
setup_t = time.perf_counter()
context = create_context(scheme)
keys = setup_keys(context)
setup_t = time.perf_counter() - setup_t
enc_t = time.perf_counter()
ct = encrypt([1, 2, 3], context, keys.pub)
enc_t = time.perf_counter() - enc_t
op_t = time.perf_counter()
ct2 = ct * ct
op_t = time.perf_counter() - op_t
return {'setup': setup_t, 'encrypt': enc_t, 'op': op_t}
```
### Threshold HE (multi-key)
```python
# 매 multi-party with shared secret
# 매 매 party 매 partial decryption share
def threshold_decrypt(ciphertext, partial_shares, threshold):
if len(partial_shares) >= threshold:
return combine_shares(partial_shares, ciphertext)
raise ThresholdNotMet()
```
### FHEVM (smart contract on encrypted)
```solidity
// 매 fhEVM (Zama)
import "fhevm/lib/TFHE.sol";
contract EncryptedAuction {
euint64 highestBid; // 매 encrypted
function bid(bytes calldata encryptedAmount) public {
euint64 amount = TFHE.asEuint64(encryptedAmount);
highestBid = TFHE.max(highestBid, amount);
}
}
```
## 매 결정 기준
| 상황 | Scheme |
|---|---|
| ML inference (real) | CKKS |
| Exact integer | BFV / BGV |
| Boolean / lookup | TFHE |
| Smart contract | FHEVM (TFHE-based) |
| Multi-party | Threshold HE |
| Best library | OpenFHE / SEAL / Concrete |
**기본값**: 매 ML = CKKS + 매 polynomial activation. 매 boolean = TFHE. 매 always benchmark before commit (100-1000x cost).
## 🔗 Graph
- 부모: [[Cryptography]] · [[Privacy-Preserving]]
- 변형: [[Fully-HE]] · [[Partial-HE]] · [[Threshold-HE]]
- 응용: [[Privacy-Preserving-ML]] · [[Federated-Learning]]
- Adjacent: [[Differential-Privacy]] · [[Secure-Multiparty-Computation]] · [[Zero-Knowledge-Proof]]
## 🤖 LLM 활용
**언제**: 매 medical / financial. 매 cloud trust. 매 multi-party compute.
**언제 X**: 매 latency-critical. 매 plaintext 의 가능.
## ❌ 안티패턴
- **FHE for everything**: 매 cost overkill.
- **No polynomial approx of activation**: 매 deep ReLU 의 hard.
- **Wrong scheme**: 매 BFV for real-valued ML.
- **No bootstrap when deep**: 매 noise overflow.
## 🧪 검증 / 중복
- Verified (Gentry 2009, CKKS 2017, OpenFHE / SEAL / Concrete docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-04-26 | Auto |
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — schemes + 매 TenSEAL / SEAL / TFHE / Concrete / FHEVM code |