Skip to content

Instantly share code, notes, and snippets.

@kjsman
Last active February 12, 2024 17:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kjsman/7430f283f0c8fefa16988d17841ed1c2 to your computer and use it in GitHub Desktop.
Save kjsman/7430f283f0c8fefa16988d17841ed1c2 to your computer and use it in GitHub Desktop.
ChaCha20-Poly1305 in 779 bytes
encrypt=async(P,Q,K,N)=>{I=-64;do{T=U=Uint32Array,J=0;O=await(A=async(...V)=>W(await(new Blob(V)).arrayBuffer()))("expand 32-byte k",K,(W=x=>new U(x))([I/64+1]),N),R=O.slice(),(D=b=>(S=[7,8,12,L=16],J<80&&(B=(W,Z,Y,X)=>(s=S.pop())&&(w=O[W]^=O[X]+=O[Y],O[W]<<=s,O[W]|=w>>>-s,B(Y,X,W,Z)))((M=i=>i*4+((J/4&1&&i)+J)%4)(3),M(2),M(1),J++%4)+D()))();for(i=L;i;O[--i]+=R[i]);U=Uint8Array;O=await A(O);P=I?P:W(P);Y=I<0?O:Y;for(i=0;i<64;i++)P[I++]^=O[i]}while(P[I]+1);r=(F=(a,i,j)=>(j??=L)?BigInt(a[i])+F(a,i+1,--j)*(Z=256n):0n)(Y,0)&0xffffffc0ffffffc0ffffffc0fffffffn;a=0n;p=P[l='length'],q=Q[l],k=(1<<30)*4,Q=await A(Q,(X=x=>W(x%L&&L-x%L))(q),P,X(p),new T([q,q/k,p,p/k]));for(I=0;Q[I]+1;I+=L)a=(a+F(Q,I)+(1n<<128n))*r%((1n<<130n)-5n);a+=F(Y,L);return[P,W(L).map(t=>(r=a%Z,a/=Z,`${r}`))]}
// All parameters are Uint8Array
// Nonce should be 12 bytes
let result = await encrypt(plaintext, aad, key, nonce)
let [ciphertext, tag] = result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment