diff --git a/src/chacha.js b/src/chacha.js --- a/src/chacha.js +++ b/src/chacha.js @@ -1,26 +1,21 @@ // https://tools.ietf.org/html/rfc7539 -import {MASK,int32s2bytes,bytes2int32s,zeroPad} from "./util.js"; +import {MASK,int32s2bytes,bytes2int32s,zeroPad,createRandomNonce} from "./util.js"; function lrot(x,shift){ return (x<>>(32-shift))&MASK; } -export function createNonce(){ - let nonce=new Uint8Array(12); - window.crypto.getRandomValues(nonce); - return Array.from(nonce); -} - /** * A Chacha20 cipher class. * @param {Array} key Array of bytes (integers: 0<=x<256). Short keys are padded to 32B, long keys are silently truncated. * @param {Array} nonce optional. If present, it must be an Array of bytes (integers: 0<=x<256). Short nonces are padded to 12B, long nonces are silently truncated. */ export function Chacha20(key,nonce){ + const NONCE_LEN=12; if(nonce===undefined){ - nonce=createNonce(); + nonce=createRandomNonce(NONCE_LEN); } - this._nonce=zeroPad(nonce,12); + this._nonce=zeroPad(nonce,NONCE_LEN); nonce=bytes2int32s(this._nonce); key=bytes2int32s(zeroPad(key,32)); @@ -85,12 +80,10 @@ Chacha20.prototype._incrementPos=functio export function encrypt(data,key,nonce){ let cipher=new Chacha20(key,nonce); nonce=cipher.getNonce(); - return nonce.concat(data.map(b=>b^cipher.getByte())); + return [nonce,data.map(b=>b^cipher.getByte())]; } -export function decrypt(data,key){ - let nonce=data.slice(0,12); - let ciphertext=data.slice(12); +export function decrypt(ciphertext,key,nonce){ let cipher=new Chacha20(key,nonce); return ciphertext.map(b=>b^cipher.getByte()); }