ECIES-X963-SHA256-AESGCM을 살펴보자.
ECIES |
ECDH(키 교환) 후 대칭키 암복호화를 수행하는 것을 의미 |
X963-SHA256 |
공유키 유도 방식 |
AES-GCM |
AES 대칭키 암호화. GCM은 MAC 역할 |
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.hashes import SHA256
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.kdf.x963kdf import X963KDF
import os
# AES-GCM 암호화 함수
def aes_gcm_encrypt(key, plaintext):
iv = os.urandom(12) # GCM IV (12바이트)
cipher = Cipher(algorithms.AES(key), modes.GCM(iv))
encryptor = cipher.encryptor()
ciphertext = encryptor.update(plaintext) + encryptor.finalize()
return iv, ciphertext, encryptor.tag # (IV, 암호문, 인증 태그)
# AES-GCM 복호화 함수
def aes_gcm_decrypt(key, iv, ciphertext, tag):
cipher = Cipher(algorithms.AES(key), modes.GCM(iv, tag))
decryptor = cipher.decryptor()
return decryptor.update(ciphertext) + decryptor.finalize()
# ECDH 키 교환 및 KDF (X9.63-KDF with SHA-256)
def derive_shared_key(private_key, peer_public_key):
shared_secret = private_key.exchange(ec.ECDH(), peer_public_key)
print(f"shared key : {shared_secret.hex()}")
kdf = X963KDF(algorithm=SHA256(), length=32, sharedinfo=None) # 256-bit AES key
return kdf.derive(shared_secret)
# 🔹 1️⃣ Alice와 Bob의 키 쌍 생성 (SECP256R1 사용)
alice_private_key = ec.generate_private_key(ec.SECP256R1())
bob_private_key = ec.generate_private_key(ec.SECP256R1())
alice_public_key = alice_private_key.public_key()
bob_public_key = bob_private_key.public_key()
# 🔹 2️⃣ Alice가 Bob의 공개 키를 받아 대칭 키 생성
alice_shared_key = derive_shared_key(alice_private_key, bob_public_key)
# 🔹 3️⃣ Bob이 Alice의 공개 키를 받아 같은 대칭 키 생성
bob_shared_key = derive_shared_key(bob_private_key, alice_public_key)
assert alice_shared_key == bob_shared_key # 키가 동일해야 함
# 🔹 4️⃣ Alice가 메시지를 암호화하여 Bob에게 전송
plaintext = b"Hello"
iv, ciphertext, tag = aes_gcm_encrypt(alice_shared_key, plaintext)
# 🔹 5️⃣ Bob이 받은 데이터를 복호화
decrypted_message = aes_gcm_decrypt(bob_shared_key, iv, ciphertext, tag)
print(f"📩 암호화된 메시지: {ciphertext.hex()}")
print(f"🔓 복호화된 메시지: {decrypted_message.decode()}")
1. alice & bob은 secp256r1 곡선으로 키 쌍 생성
2. alice/bob 개인키와 bob/alice 공개키로 ECDH 수행하여 공유키 유도
3. 공유키를 키 유도(X.963-SHA256)하여 공유 AES 대칭키 유도
4. 공유 AES 대칭 키로 AES-GCM 수행