diff --git a/e-voting-system/backend/routes/admin.py b/e-voting-system/backend/routes/admin.py index 7f5fc96..4812575 100644 --- a/e-voting-system/backend/routes/admin.py +++ b/e-voting-system/backend/routes/admin.py @@ -155,7 +155,11 @@ async def init_election_keys(election_id: int, db: Session = Depends(get_db)): pubkey_is_invalid = False if election.public_key: try: - pubkey_str = election.public_key.decode('utf-8') if isinstance(election.public_key, bytes) else str(election.public_key) + # Public key is stored as base64-encoded bytes, try to decode it + pubkey_b64_str = election.public_key.decode('ascii') if isinstance(election.public_key, bytes) else str(election.public_key) + # Try to decode the base64 to verify it's valid + pubkey_bytes = base64.b64decode(pubkey_b64_str) + pubkey_str = pubkey_bytes.decode('utf-8') # Check if it's valid (should be "p:g:h" format, not "pk_ongoing_X") if not ':' in pubkey_str or pubkey_str.startswith('pk_') or pubkey_str.startswith('b\''): pubkey_is_invalid = True @@ -165,8 +169,8 @@ async def init_election_keys(election_id: int, db: Session = Depends(get_db)): if not election.public_key or pubkey_is_invalid: logger.info(f"Generating ElGamal public key for election {election_id}") elgamal = ElGamalEncryption(p=election.elgamal_p or 23, g=election.elgamal_g or 5) - # Use the property that returns properly formatted bytes "p:g:h" - election.public_key = elgamal.public_key_bytes + # Store as base64-encoded bytes (public_key_bytes returns UTF-8 "p:g:h", then encode to base64) + election.public_key = base64.b64encode(elgamal.public_key_bytes) db.commit() logger.info(f"✓ Generated public key for election {election_id}") else: @@ -179,7 +183,7 @@ async def init_election_keys(election_id: int, db: Session = Depends(get_db)): "elgamal_p": election.elgamal_p, "elgamal_g": election.elgamal_g, "public_key_generated": True, - "public_key": base64.b64encode(election.public_key).decode() if election.public_key else None + "public_key": election.public_key.decode('ascii') if isinstance(election.public_key, bytes) else election.public_key } except HTTPException: diff --git a/e-voting-system/backend/routes/votes.py b/e-voting-system/backend/routes/votes.py index 2a2e2f0..6bcd533 100644 --- a/e-voting-system/backend/routes/votes.py +++ b/e-voting-system/backend/routes/votes.py @@ -510,7 +510,7 @@ async def setup_election( "status": "initialized", "election_id": election_id, "public_keys": { - "elgamal_pubkey": election.public_key.decode('utf-8') if election.public_key else None + "elgamal_pubkey": election.public_key.decode('ascii') if isinstance(election.public_key, bytes) else election.public_key }, "blockchain_blocks": blockchain.get_block_count() } @@ -547,7 +547,7 @@ async def get_public_keys( ) return { - "elgamal_pubkey": election.public_key.decode('utf-8') if election.public_key else None + "elgamal_pubkey": election.public_key.decode('ascii') if isinstance(election.public_key, bytes) else election.public_key }