TEE 모델은 하드웨어로 보호된 enclave(Intel TDX, NVIDIA Confidential Computing) 안에서 실행됩니다. 추론 중에 모델 가중치와 사용자 데이터는 enclave 내부에서 보호되며 호스트 시스템으로부터 격리됩니다. TEE 전용 요청도 다른 모델에 대한 요청과 마찬가지로 평문 상태로 Venice API에 도달합니다. Venice가 암호문만 전달하도록 하려면 E2EE를 사용하세요.
import requestsdef get_e2ee_models(api_key: str) -> list: """E2EE를 지원하는 모델 목록을 가져옵니다.""" response = requests.get( 'https://api.venice.ai/api/v1/models', headers={'Authorization': f'Bearer {api_key}'} ) models = response.json()['data'] return [ model for model in models if model.get('model_spec', {}).get('capabilities', {}).get('supportsE2EE') ]# 사용 예시models = get_e2ee_models('your-api-key')print('E2EE Models:', [m['id'] for m in models])
2단계: 임시 키 쌍 생성
각 세션마다 새 키 쌍을 생성합니다. private key는 메모리에만 보관하고 사용 후 안전하게 0으로 채워야 합니다.
import { ec as EC } from 'elliptic'function generateEphemeralKeyPair() { const ec = new EC('secp256k1') const keyPair = ec.genKeyPair() return { privateKey: new Uint8Array(keyPair.getPrivate().toArray('be', 32)), publicKeyHex: keyPair.getPublic('hex'), // 비압축 포맷 (65바이트 hex) }}// 보안: 사용 종료 후 private key를 0으로 채우기function zeroFill(arr) { arr.fill(0)}
from ecdsa import SECP256k1, SigningKeyimport secretsdef generate_ephemeral_key_pair(): """E2EE 세션을 위한 임시 secp256k1 키 쌍을 생성합니다.""" private_key = SigningKey.generate(curve=SECP256k1) public_key = private_key.get_verifying_key() # 비압축 공개 키 가져오기 (04 || x || y) public_key_bytes = b'\x04' + public_key.to_string() return { 'private_key': private_key.to_string(), # 32 바이트 'public_key_hex': public_key_bytes.hex() # 130 hex 문자 }
검증 헬퍼
요청을 보내기 전에 키와 암호화된 콘텐츠를 검증하려면 다음 헬퍼 함수를 사용하세요.
function validateClientPubkey(pubkeyHex) { if (pubkeyHex.length !== 130 || !pubkeyHex.startsWith('04')) { throw new Error(`Client pubkey must be 130 hex chars starting with '04' (got ${pubkeyHex.length})`) }}function isValidEncrypted(s) { // 최소: ephemeral_pub (65) + nonce (12) + tag (16) = 93 바이트 = 186 hex 문자 return s.length >= 186 && /^[0-9a-fA-F]+$/.test(s)}
def validate_client_pubkey(pubkey_hex: str) -> None: """클라이언트 공개 키 포맷 검증.""" if len(pubkey_hex) != 130 or not pubkey_hex.startswith('04'): raise ValueError(f"Client pubkey must be 130 hex chars starting with '04' (got {len(pubkey_hex)})")def is_valid_encrypted(s: str) -> bool: """유효한 hex 암호 콘텐츠인지 확인.""" # 최소: ephemeral_pub (65) + nonce (12) + tag (16) = 93 바이트 = 186 hex 문자 return len(s) >= 186 and all(c in '0123456789abcdefABCDEF' for c in s)
3단계: TEE Attestation 가져오기 및 검증
attestation은 모델이 진짜 TEE에서 실행되고 있음을 증명합니다. 모델의 공개 키를 신뢰하기 전에 항상 attestation을 검증하세요.
중요: Nonce 길이 — 클라이언트 nonce는 32바이트(64 hex 문자) 여야 합니다. 일부 TEE 공급자는 정확히 32바이트를 요구하며 더 짧은 nonce는 거부합니다.
import crypto from 'crypto'async function fetchAndVerifyAttestation(modelId, apiKey) { // 재전송 방지를 위한 클라이언트 nonce 생성 (32바이트 = 64 hex 문자) const clientNonce = crypto.randomBytes(32).toString('hex') const response = await fetch( `https://api.venice.ai/api/v1/tee/attestation?model=${encodeURIComponent(modelId)}&nonce=${clientNonce}`, { headers: { Authorization: `Bearer ${apiKey}` } } ) const attestation = await response.json() // attestation 검증 if (attestation.verified !== true) { throw new Error('TEE attestation verification failed on server') } if (attestation.nonce !== clientNonce) { throw new Error('Attestation nonce mismatch - possible replay attack') } // 암호화용 모델 공개 키 가져오기 const modelPublicKey = attestation.signing_key || attestation.signing_public_key if (!modelPublicKey) { throw new Error('No signing key in attestation response') } return { modelPublicKey, signingAddress: attestation.signing_address, attestation, }}
import secretsimport requestsdef fetch_and_verify_attestation(model_id: str, api_key: str) -> dict: """모델에 대한 TEE attestation을 가져오고 검증합니다.""" # 재전송 방지를 위한 클라이언트 nonce 생성 (32바이트 = 64 hex 문자) client_nonce = secrets.token_hex(32) response = requests.get( f'https://api.venice.ai/api/v1/tee/attestation', params={'model': model_id, 'nonce': client_nonce}, headers={'Authorization': f'Bearer {api_key}'} ) attestation = response.json() # attestation 검증 if attestation.get('verified') != True: raise ValueError('TEE attestation verification failed on server') if attestation.get('nonce') != client_nonce: raise ValueError('Attestation nonce mismatch - possible replay attack') # 암호화용 모델 공개 키 가져오기 model_public_key = attestation.get('signing_key') or attestation.get('signing_public_key') if not model_public_key: raise ValueError('No signing key in attestation response') return { 'model_public_key': model_public_key, 'signing_address': attestation.get('signing_address'), 'attestation': attestation }
4단계: 메시지 암호화
전송 전에 user 및 system 메시지를 암호화합니다. user와 system 역할 메시지만 암호화하면 됩니다.
E2EE 헤더가 있는 경우, 모든user 및 system 역할 메시지는 암호화되어야 합니다. 이 역할에 평문 콘텐츠를 보내면 “Encrypted field is not valid hex” 에러가 발생합니다.
import { gcm } from '@noble/ciphers/aes.js'import { hkdf } from '@noble/hashes/hkdf.js'import { sha256 } from '@noble/hashes/sha2.js'import { ec as EC } from 'elliptic'import crypto from 'crypto'const HKDF_INFO = new TextEncoder().encode('ecdsa_encryption')function encryptMessage(plaintext, modelPublicKeyHex) { const ec = new EC('secp256k1') // 공개 키 정규화 (필요 시 04 prefix 추가) let normalizedKey = modelPublicKeyHex if (!normalizedKey.startsWith('04') && normalizedKey.length === 128) { normalizedKey = '04' + normalizedKey } const modelPublicKey = ec.keyFromPublic(normalizedKey, 'hex') // 이 메시지를 위한 임시 키 쌍 생성 const ephemeralKeyPair = ec.genKeyPair() // ECDH 공유 비밀 const sharedSecret = ephemeralKeyPair.derive(modelPublicKey.getPublic()) const sharedSecretBytes = new Uint8Array(sharedSecret.toArray('be', 32)) // HKDF로 AES 키 파생 const aesKey = hkdf(sha256, sharedSecretBytes, undefined, HKDF_INFO, 32) // 무작위 nonce 생성 const nonce = crypto.randomBytes(12) // AES-GCM 으로 암호화 const cipher = gcm(aesKey, nonce) const encrypted = cipher.encrypt(new TextEncoder().encode(plaintext)) // 임시 공개 키 가져오기 (비압축) const ephemeralPublic = new Uint8Array(ephemeralKeyPair.getPublic(false, 'array')) // 결합: ephemeral_public (65바이트) + nonce (12바이트) + ciphertext const result = new Uint8Array(65 + 12 + encrypted.length) result.set(ephemeralPublic, 0) result.set(nonce, 65) result.set(encrypted, 65 + 12) return Buffer.from(result).toString('hex')}function encryptMessagesForE2EE(messages, modelPublicKey) { return messages.map(msg => { if (msg.role === 'user' || msg.role === 'system') { return { ...msg, content: encryptMessage(msg.content, modelPublicKey), } } return msg })}
from cryptography.hazmat.primitives.ciphers.aead import AESGCMfrom cryptography.hazmat.primitives.kdf.hkdf import HKDFfrom cryptography.hazmat.primitives import hashesfrom ecdsa import SECP256k1, VerifyingKey, SigningKeyimport osHKDF_INFO = b'ecdsa_encryption'def encrypt_message(plaintext: str, model_public_key_hex: str) -> str: """ECDH + HKDF + AES-GCM을 사용해 메시지를 암호화.""" # 공개 키 정규화 key_hex = model_public_key_hex if not key_hex.startswith('04') and len(key_hex) == 128: key_hex = '04' + key_hex model_public_key_bytes = bytes.fromhex(key_hex) # 모델의 공개 키 파싱 (04 prefix 생략) model_verifying_key = VerifyingKey.from_string( model_public_key_bytes[1:], curve=SECP256k1 ) # 이 메시지를 위한 임시 키 쌍 생성 ephemeral_private = SigningKey.generate(curve=SECP256k1) ephemeral_public = ephemeral_private.get_verifying_key() # ECDH: 공유 비밀 계산 shared_point = model_verifying_key.pubkey.point * ephemeral_private.privkey.secret_multiplier shared_secret = shared_point.x().to_bytes(32, 'big') # HKDF로 AES 키 파생 hkdf = HKDF( algorithm=hashes.SHA256(), length=32, salt=None, info=HKDF_INFO, ) aes_key = hkdf.derive(shared_secret) # 무작위 nonce 생성 nonce = os.urandom(12) # AES-GCM 으로 암호화 aesgcm = AESGCM(aes_key) ciphertext = aesgcm.encrypt(nonce, plaintext.encode('utf-8'), None) # 임시 공개 키 가져오기 (비압축: 04 || x || y) ephemeral_public_bytes = b'\x04' + ephemeral_public.to_string() # 결합: ephemeral_public (65바이트) + nonce (12바이트) + ciphertext result = ephemeral_public_bytes + nonce + ciphertext return result.hex()def encrypt_messages_for_e2ee(messages: list, model_public_key: str) -> list: """user 및 system 메시지를 암호화.""" encrypted_messages = [] for msg in messages: if msg['role'] in ('user', 'system'): encrypted_messages.append({ **msg, 'content': encrypt_message(msg['content'], model_public_key) }) else: encrypted_messages.append(msg) return encrypted_messages
models = client.models.list()for model in models.data: caps = getattr(model, 'model_spec', {}).get('capabilities', {}) if caps.get('supportsTeeAttestation') or caps.get('supportsE2EE'): print(f"{model.id}: TEE={caps.get('supportsTeeAttestation')}, E2EE={caps.get('supportsE2EE')}")
에러 처리
Error
Cause
Solution
TEE attestation verification failed
attestation 검증 실패
재시도하거나 지원에 문의
Attestation nonce mismatch
재전송 공격 가능성
새 nonce 생성
TDX debug mode detected
enclave가 디버그 모드
프로덕션에서 사용 금지
Failed to decrypt field
서버 측 E2EE 복호화 실패
암호화 구현 확인
Encrypted field is not valid hex
E2EE 헤더와 함께 평문 전송
모든 user/system 메시지를 암호화
Invalid public key
잘못된 키 포맷
04로 시작하는 130 hex 문자 사용
문제 해결
502 Bad Gateway 또는 'Nonce must be exactly 32 bytes'
nonce 길이가 잘못되었습니다. TEE 공급자는 정확히 32바이트(64 hex 문자) 를 요구합니다.
crypto.randomBytes(32).toString('hex') (JS) 또는 secrets.token_hex(32) (Python) 사용
흔한 실수: secrets.token_hex(16)은 32 hex 문자(16바이트)를 생성하며 32바이트가 아닙니다