from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import serialization
from cryptography.exceptions import InvalidSignature
import json
# --- Key Generation (Ideally done once and keys stored securely) ---
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048
)
public_key = private_key.public_key()
# Serialize the public key for storage (e.g., in a file or database)
public_key_pem = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
# --- Signing (on the sending side) ---
def sign_message(message, private_key):
message_bytes = message.encode('utf-8')
hasher = hashes.Hash(hashes.SHA256())
hasher.update(message_bytes)
digest = hasher.finalize()
signature = private_key.sign(
digest,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
return signature.hex()
# --- Verification (on the LLM side) ---
def verify_message(message, signature, public_key_pem):
try:
public_key = serialization.load_pem_public_key(public_key_pem)
message_bytes = message.encode('utf-8')
hasher = hashes.Hash(hashes.SHA256())
hasher.update(message_bytes)
digest = hasher.finalize()
public_key.verify(
bytes.fromhex(signature),
digest,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
return True # Signature is valid
except InvalidSignature:
return False # Signature is invalid
except Exception as e:
print(f"Verification error: {e}")
return False
# --- Example Usage ---
message_to_send = "This is a test message for the LLM."
signature = sign_message(message_to_send, private_key)
# Simulate sending the message and signature
received_message = message_to_send
received_signature = signature
is_valid = verify_message(received_message, received_signature, public_key_pem)
if is_valid:
print("Message is authentic!")
# Process the message with the LLM
else:
print("Message is not authentic! Rejecting.")
In summary: Securing an open-source LLM with cryptographic authentication is a complex but potentially valuable undertaking. It involves careful key management, message signing and verification, and integration with the LLM's architecture. Be prepared for performance overhead and the need for ongoing security monitoring and maintenance. Start with a thorough understanding of cryptography and the specific LLM you are working with. Good luck!