06Python · executable cell
PYTHON · Code cell
# =====================================================================
# K15 | Code cell 02 | K15 · Ascon-AEAD128 · lightweight authenticated encryption
# 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.
# =====================================================================
#!/usr/bin/env python3
"""Byte-oriented educational Ascon-AEAD128, NIST SP 800-232 (2025).
Not hardened or validated for production. No secret inputs or external services.
"""
import hmac, json, os
# Set MASK for the next computation or reference condition.
MASK=(1<<64)-1
# Set IV for the next computation or reference condition.
IV=0x00001000808c0001
# Set RC for the next computation or reference condition.
RC=(0xf0,0xe1,0xd2,0xc3,0xb4,0xa5,0x96,0x87,0x78,0x69,0x5a,0x4b)
# Define the reusable operation rot; keep its logic separate from the trial.
def rot(x,n): return ((x>>n)|(x<<(64-n)))&MASK
# Define the reusable operation perm; keep its logic separate from the trial.
def perm(s,rounds):
for c in RC[-rounds:]:
a,b,d,e,f=s; d^=c
a^=f; f^=e; d^=b
t=[a,b,d,e,f]; u=[t[i]^((~t[(i+1)%5])&t[(i+2)%5]) for i in range(5)]
u[1]^=u[0]; u[0]^=u[4]; u[3]^=u[2]; u[2]=(~u[2])&MASK
s[:]=[x^rot(x,i)^rot(x,j) for x,(i,j) in zip(u,[(19,28),(61,39),(1,6),(10,17),(7,41)])]
# Define the reusable operation word; keep its logic separate from the trial.
def word(b): return int.from_bytes(b,'little')
# Define the reusable operation rate; keep its logic separate from the trial.
def rate(s): return s[0].to_bytes(8,'little')+s[1].to_bytes(8,'little')
# Define the reusable operation setrate; keep its logic separate from the trial.
def setrate(s,b): s[0],s[1]=word(b[:8]),word(b[8:])
# Define the reusable operation xor; keep its logic separate from the trial.
def xor(a,b):return bytes(x^y for x,y in zip(a,b))
# Define the reusable operation init; keep its logic separate from the trial.
def init(key,nonce,ad):
if len(key)!=16 or len(nonce)!=16:raise ValueError('128-bit key and nonce required')
k0,k1=word(key[:8]),word(key[8:]);s=[IV,k0,k1,word(nonce[:8]),word(nonce[8:])];perm(s,12);s[3]^=k0;s[4]^=k1
if ad:
padded=ad+b'\x01'+b'\0'*((15-len(ad))%16)
for i in range(0,len(padded),16):setrate(s,xor(rate(s),padded[i:i+16]));perm(s,8)
s[4]^=1<<63
return s,k0,k1
# Define the reusable operation finish; keep its logic separate from the trial.
def finish(s,k0,k1):
s[2]^=k0;s[3]^=k1;perm(s,12);s[3]^=k0;s[4]^=k1
return s[3].to_bytes(8,'little')+s[4].to_bytes(8,'little')
# Define the reusable operation encrypt; keep its logic separate from the trial.
def encrypt(key,nonce,ad,plain):
s,k0,k1=init(key,nonce,ad);out=bytearray()
for i in range(0,len(plain)//16*16,16):
setrate(s,xor(rate(s),plain[i:i+16]));out.extend(rate(s));perm(s,8)
tail=plain[len(plain)//16*16:];setrate(s,xor(rate(s),tail+b'\x01'+b'\0'*(15-len(tail))));out.extend(rate(s)[:len(tail)])
return bytes(out)+finish(s,k0,k1)
# Define the reusable operation decrypt; keep its logic separate from the trial.
def decrypt(key,nonce,ad,combined):
if len(combined)<16:raise ValueError('Missing tag')
c,tag=combined[:-16],combined[-16:];s,k0,k1=init(key,nonce,ad);out=bytearray()
for i in range(0,len(c)//16*16,16):
block=c[i:i+16];out.extend(xor(rate(s),block));setrate(s,block);perm(s,8)
tail=c[len(c)//16*16:];r=rate(s);out.extend(xor(r,tail));new=bytearray(tail+r[len(tail):]);new[len(tail)]^=1;setrate(s,new)
if not hmac.compare_digest(tag,finish(s,k0,k1)):raise ValueError('Authentication failed')
return bytes(out)
# Define the reusable operation checks; keep its logic separate from the trial.
def checks():
# Independent RustCrypto ascon-aead 0.6.0 test vector Count=1 (SP 800-232).
# https://docs.rs/crate/ascon-aead/0.6.0/source/tests/data/ascon128.txt
k=bytes(range(16));n=k;expected=bytes.fromhex('4427D64B8E1E1451FC445960F0839BB0');actual=encrypt(k,n,b'',b'')
results=[{'control':'independent empty-message KAT','pass':actual==expected,'actual':actual.hex(),'expected':expected.hex()}]
for count,ml,al,hexout in [(2,0,1,'103AB79D913A0321287715A979BB8585'),(33,0,32,'22133A313FBF0B38029A45870AADC542'),(34,1,0,'E79F58F1F541FC51B5D438F8E1DD03F147'),(35,1,1,'25EB4B700ED4AC8517DCBA20F673292230'),(53,1,19,'64E8A535661ECD9BD9986CEA0A46A8556B')]:
expected=bytes.fromhex(hexout);pt=bytes(range(ml));ad=bytes(range(al));actual=encrypt(k,n,ad,pt)
results.append({'control':f'independent KAT {count}','pass':actual==expected and decrypt(k,n,ad,expected)==pt,'actual':actual.hex(),'expected':expected.hex()})
# Fresh key per run, unique nonce for every encryption. Vectors use fixed public inputs only.
k=os.urandom(16)
for size in [0,1,15,16,17,31,32,33,128]:
for alen in [0,1,16,17]:
nonce=(size*100+alen).to_bytes(16,'little');msg=bytes(range(size));ad=b'A'*alen;ct=encrypt(k,nonce,ad,msg)
results.append({'control':f'roundtrip-{size}-{alen}','pass':decrypt(k,nonce,ad,ct)==msg})
for label,nn,aa,cc in [('tag',nonce,ad,ct[:-1]+bytes([ct[-1]^1])),('associated-data',nonce,ad+b'!',ct),('nonce',bytes([nonce[0]^1])+nonce[1:],ad,ct)]+([('ciphertext',nonce,ad,bytes([ct[0]^1])+ct[1:])] if size else []):
try:decrypt(k,nn,aa,cc);ok=False
except ValueError:ok=True
results.append({'control':f'reject-{label}-{size}-{alen}','pass':ok})
return {'schema':'psut-security-evidence-157','experiment':'K15','source':'actual-local-educational-crypto','implementation':'byte-oriented teaching implementation; not production hardened','checks':results,'pass':all(x['pass'] for x in results)}
Ask Dr. Mohammad about this cell09Instructions · Markdown
## Original portal implementation (reference only)
These are the actual laboratory snippets. They are retained for comparison; follow the portal setup for WSL, hardware or services. They are **not** executed by Run all.
```bash
cd ~/kali-labs
python3 ascon_course.py
```
```bash
cd ~/kali-labs
mkdir -p ~/psut-security-results
python3 ascon_course.py > ~/psut-security-results/K15-evidence.json && cat ~/psut-security-results/K15-evidence.json
```
```python
#!/usr/bin/env python3
"""Byte-oriented educational Ascon-AEAD128, NIST SP 800-232 (2025).
Not hardened or validated for production. No secret inputs or external services.
"""
import hmac, json, os
MASK=(1<<64)-1
IV=0x00001000808c0001
RC=(0xf0,0xe1,0xd2,0xc3,0xb4,0xa5,0x96,0x87,0x78,0x69,0x5a,0x4b)
def rot(x,n): return ((x>>n)|(x<<(64-n)))&MASK
def perm(s,rounds):
for c in RC[-rounds:]:
a,b,d,e,f=s; d^=c
a^=f; f^=e; d^=b
t=[a,b,d,e,f]; u=[t[i]^((~t[(i+1)%5])&t[(i+2)%5]) for i in range(5)]
u[1]^=u[0]; u[0]^=u[4]; u[3]^=u[2]; u[2]=(~u[2])&MASK
s[:]=[x^rot(x,i)^rot(x,j) for x,(i,j) in zip(u,[(19,28),(61,39),(1,6),(10,17),(7,41)])]
def word(b): return int.from_bytes(b,'little')
def rate(s): return s[0].to_bytes(8,'little')+s[1].to_bytes(8,'little')
def setrate(s,b): s[0],s[1]=word(b[:8]),word(b[8:])
def xor(a,b):return bytes(x^y for x,y in zip(a,b))
def init(key,nonce,ad):
if len(key)!=16 or len(nonce)!=16:raise ValueError('128-bit key and nonce required')
k0,k1=word(key[:8]),word(key[8:]);s=[IV,k0,k1,word(nonce[:8]),word(nonce[8:])];perm(s,12);s[3]^=k0;s[4]^=k1
if ad:
padded=ad+b'\x01'+b'\0'*((15-len(ad))%16)
for i in range(0,len(padded),16):setrate(s,xor(rate(s),padded[i:i+16]));perm(s,8)
s[4]^=1<<63
return s,k0,k1
def finish(s,k0,k1):
s[2]^=k0;s[3]^=k1;perm(s,12);s[3]^=k0;s[4]^=k1
return s[3].to_bytes(8,'little')+s[4].to_bytes(8,'little')
def encrypt(key,nonce,ad,plain):
s,k0,k1=init(key,nonce,ad);out=bytearray()
for i in range(0,len(plain)//16*16,16):
setrate(s,xor(rate(s),plain[i:i+16]));out.extend(rate(s));perm(s,8)
tail=plain[len(plain)//16*16:];setrate(s,xor(rate(s),tail+b'\x01'+b'\0'*(15-len(tail))));out.extend(rate(s)[:len(tail)])
return bytes(out)+finish(s,k0,k1)
def decrypt(key,nonce,ad,combined):
if len(combined)<16:raise ValueError('Missing tag')
c,tag=combined[:-16],combined[-16:];s,k0,k1=init(key,nonce,ad);out=bytearray()
for i in range(0,len(c)//16*16,16):
block=c[i:i+16];out.extend(xor(rate(s),block));setrate(s,block);perm(s,8)
tail=c[len(c)//16*16:];r=rate(s);out.extend(xor(r,tail));new=bytearray(tail+r[len(tail):]);new[len(tail)]^=1;setrate(s,new)
if not hmac.compare_digest(tag,finish(s,k0,k1)):raise ValueError('Authentication failed')
return bytes(out)
def checks():
# Independent RustCrypto ascon-aead 0.6.0 test vector Count=1 (SP 800-232).
# https://docs.rs/crate/ascon-aead/0.6.0/source/tests/data/ascon128.txt
k=bytes(range(16));n=k;expected=bytes.fromhex('4427D64B8E1E1451FC445960F0839BB0');actual=encrypt(k,n,b'',b'')
results=[{'control':'independent empty-message KAT','pass':actual==expected,'actual':actual.hex(),'expected':expected.hex()}]
for count,ml,al,hexout in [(2,0,1,'103AB79D913A0321287715A979BB8585'),(33,0,32,'22133A313FBF0B38029A45870AADC542'),(34,1,0,'E79F58F1F541FC51B5D438F8E1DD03F147'),(35,1,1,'25EB4B700ED4AC8517DCBA20F673292230'),(53,1,19,'64E8A535661ECD9BD9986CEA0A46A8556B')]:
expected=bytes.fromhex(hexout);pt=bytes(range(ml));ad=bytes(range(al));actual=encrypt(k,n,ad,pt)
results.append({'control':f'independent KAT {count}','pass':actual==expected and decrypt(k,n,ad,expected)==pt,'actual':actual.hex(),'expected':expected.hex()})
# Fresh key per run, unique nonce for every encryption. Vectors use fixed public inputs only.
k=os.urandom(16)
for size in [0,1,15,16,17,31,32,33,128]:
for alen in [0,1,16,17]:
nonce=(size*100+alen).to_bytes(16,'little');msg=bytes(range(size));ad=b'A'*alen;ct=encrypt(k,nonce,ad,msg)
results.append({'control':f'roundtrip-{size}-{alen}','pass':decrypt(k,nonce,ad,ct)==msg})
for label,nn,aa,cc in [('tag',nonce,ad,ct[:-1]+bytes([ct[-1]^1])),('associated-data',nonce,ad+b'!',ct),('nonce',bytes([nonce[0]^1])+nonce[1:],ad,ct)]+([('ciphertext',nonce,ad,bytes([ct[0]^1])+ct[1:])] if size else []):
try:decrypt(k,nn,aa,cc);ok=False
except ValueError:ok=True
results.append({'control':f'reject-{label}-{size}-{alen}','pass':ok})
return {'schema':'psut-security-evidence-157','experiment':'K15','source':'actual-local-educational-crypto','implementation':'byte-oriented teaching implementation; not production hardened','checks':results,'pass':all(x['pass'] for x in results)}
if __name__=='__main__':
r=checks();print(json.dumps(r,indent=2));raise SystemExit(0 if r['pass'] else 1)
```