"""
点对点加密器实现模块
"""
import hashlib
from Crypto.Cipher import AES
from Crypto import Random

class P2PEncryptor:
    """
    点对点加密器类，提供动态加密/解密功能
    """
    
    def __init__(self, key=None, dynamic_iv=True):
        """
        初始化加密器
        
        :param key: 加密密钥，如果为None则自动生成
        :param dynamic_iv: 是否使用动态IV，默认为True
        """
        if key is None:
            self.key = Random.get_random_bytes(32)
        else:
            self.key = hashlib.sha256(key.encode()).digest()
        self.dynamic_iv = dynamic_iv
        
    def encrypt(self, plaintext):
        """
        动态加密数据
        
        :param plaintext: 明文数据
        :return: 加密后的数据 (IV + 密文)
        """
        if self.dynamic_iv:
            iv = Random.get_random_bytes(AES.block_size)
        else:
            iv = hashlib.sha256(self.key).digest()[:AES.block_size]
            
        cipher = AES.new(self.key, AES.MODE_CFB, iv)
        ciphertext = cipher.encrypt(plaintext.encode())
        return iv + ciphertext
    
    def decrypt(self, ciphertext):
        """
        解密数据
        
        :param ciphertext: 密文数据 (IV + 密文)
        :return: 解密后的明文
        """
        iv = ciphertext[:AES.block_size]
        cipher = AES.new(self.key, AES.MODE_CFB, iv)
        plaintext = cipher.decrypt(ciphertext[AES.block_size:])
        return plaintext.decode()
        
    def generate_session_key(self):
        """
        生成会话密钥
        
        :return: 随机生成的会话密钥
        """
        return Random.get_random_bytes(32)