Startonix / Modular-AI

Advanced AI Training and Building Repository
0 stars 0 forks source link

Hybrid Encryption #179

Open Startonix opened 5 months ago

Startonix commented 5 months ago

import os import hashlib from Crypto.Cipher import AES from Crypto.PublicKey import ECC from Crypto.Signature import DSS from Crypto.Hash import SHA256 from ntru import NtruEncrypt import pqcrypto

Hybrid Encryption using ECC and AES

class HybridEncryption: def init(self): self.ecc_key = ECC.generate(curve='secp256k1') self.ntru = NtruEncrypt()

def generate_aes_key(self):
    return os.urandom(32)  # AES-256 key

def encrypt_aes(self, data, aes_key):
    cipher = AES.new(aes_key, AES.MODE_GCM)
    ciphertext, tag = cipher.encrypt_and_digest(data)
    return cipher.nonce, ciphertext, tag

def decrypt_aes(self, aes_key, nonce, ciphertext, tag):
    cipher = AES.new(aes_key, AES.MODE_GCM, nonce=nonce)
    return cipher.decrypt_and_verify(ciphertext, tag)

def encrypt_session_key(self, aes_key):
    public_key = self.ecc_key.public_key()
    return public_key.encrypt(aes_key)

def decrypt_session_key(self, encrypted_key):
    return self.ecc_key.decrypt(encrypted_key)

def sign_data(self, data):
    h = SHA256.new(data)
    signer = DSS.new(self.ecc_key, 'fips-186-3')
    return signer.sign(h)

def verify_signature(self, data, signature):
    h = SHA256.new(data)
    verifier = DSS.new(self.ecc_key.public_key(), 'fips-186-3')
    try:
        verifier.verify(h, signature)
        return True
    except ValueError:
        return False

def encrypt_data(self, data):
    aes_key = self.generate_aes_key()
    nonce, ciphertext, tag = self.encrypt_aes(data, aes_key)
    encrypted_key = self.encrypt_session_key(aes_key)
    signature = self.sign_data(ciphertext)
    return encrypted_key, nonce, ciphertext, tag, signature

def decrypt_data(self, encrypted_key, nonce, ciphertext, tag, signature):
    aes_key = self.decrypt_session_key(encrypted_key)
    if not self.verify_signature(ciphertext, signature):
        raise ValueError("Invalid Signature")
    return self.decrypt_aes(aes_key, nonce, ciphertext, tag)

Example Usage

data = b"Sensitive information"

Initialize HybridEncryption

hybrid_encryption = HybridEncryption()

Encrypt data

encrypted_key, nonce, ciphertext, tag, signature = hybrid_encryption.encrypt_data(data)

Decrypt data

decrypted_data = hybrid_encryption.decrypt_data(encrypted_key, nonce, ciphertext, tag, signature)

print(f"Original: {data}") print(f"Decrypted: {decrypted_data}")