PYTHON · Code cell
# =====================================================================
# K08 | Code cell 02 | K08 · Authenticated encryption & signatures
# Purpose: 3. Implementation Read the comments and variable definitions before execution. Assertions must pass; inspect values, not just completion.
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
import json, secrets, time
from pathlib import Path
# Set HOME for the next computation or reference condition.
HOME=Path.home()/'.psut-kali-security-v14'
# Define the reusable operation save; keep its logic separate from the trial.
def save(name, tests):
report={'schema':'psut-kali-v14','experiment':name,'source':'local-execution-self-reported','utc':time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()),'checks':tests}
out=HOME/'evidence'; out.mkdir(parents=True,exist_ok=True,mode=0o700)
(out/(name+'.json')).write_text(json.dumps(report,indent=2)+'\n')
print(json.dumps(report,indent=2)); return all(x['pass'] for x in tests)
# Define the reusable operation check; keep its logic separate from the trial.
def check(name, ok, observation): return {'name':name,'pass':bool(ok),'observation':str(observation)}
# Define the reusable operation crypto; keep its logic separate from the trial.
def crypto():
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.exceptions import InvalidTag,InvalidSignature
a=b'PSUT fictional telemetry'; b=a+b' changed'; aad=b'demo-device'; key=AESGCM.generate_key(bit_length=128);g=AESGCM(key);nonce=secrets.token_bytes(12);ct=g.encrypt(nonce,a,aad);tests=[check('AES-GCM round trip',g.decrypt(nonce,ct,aad)==a,'original verified')]
for name,modified,associated in [('Altered ciphertext',ct[:-1]+bytes([ct[-1]^1]),aad),('Altered AAD',ct,b'wrong-device')]:
try:g.decrypt(nonce,modified,associated);ok=False
except InvalidTag:ok=True
tests.append(check(name,ok,'authentication rejection expected'))
e=ec.generate_private_key(ec.SECP256R1());r=rsa.generate_private_key(public_exponent=65537,key_size=2048);pss=padding.PSS(mgf=padding.MGF1(hashes.SHA256()),salt_length=padding.PSS.MAX_LENGTH)
for name,priv,args in [('ECDSA P-256',e,[ec.ECDSA(hashes.SHA256())]),('RSA-PSS',r,[pss,hashes.SHA256()])]:
sig=priv.sign(a,*args);priv.public_key().verify(sig,a,*args);tests.append(check(name+' original',True,'signature verifies'))
try:priv.public_key().verify(sig,b,*args);ok=False
except InvalidSignature:ok=True
tests.append(check(name+' altered',ok,'signature rejected'))
# NIST GCM zero-key/IV, empty plaintext reference case; never use this key outside a KAT.
kat=AESGCM(bytes(16)).encrypt(bytes(12),b'',None).hex()
tests.append(check('AES-GCM known answer',kat=='58e2fccefa7e3061367f1d57a4e7455a','fixed reference tag'))
alice=ec.generate_private_key(ec.SECP256R1());bob=ec.generate_private_key(ec.SECP256R1())
def derive(secret):return HKDF(algorithm=hashes.SHA256(),length=16,salt=None,info=b'PSUT teaching ECDH').derive(secret)
tests.append(check('ECDH/HKDF agreement',derive(alice.exchange(ec.ECDH(),bob.public_key()))==derive(bob.exchange(ec.ECDH(),alice.public_key())),'agreement only; peer authentication still required'))
return save('K08-CRYPTO',tests)