@li0ard/kalyna
Version:
Kalyna (DSTU 7624:2014) cipher implementation in pure TypeScript
25 lines (24 loc) • 831 B
JavaScript
import { concatBytes, xor } from "@li0ard/gost3413/dist/utils.js";
const incrementCounterAt = (ctr, pos) => {
let j = pos;
while (j < ctr.length)
if (++ctr[j++] != 0)
break;
};
/**
* Proceed data using the Counter (CTR) mode
* @param cipherClass Initialized cipher class
* @param data Data to be encrypted/decrypted
* @param iv Initialization vector
*/
export const ctr = (cipherClass, data, iv) => {
if (iv.length !== cipherClass.blockSize)
throw new Error("Invalid IV size");
const keystreamBlocks = [];
const ctr = cipherClass.encrypt(iv);
for (let i = 0; i < Math.ceil(data.length / cipherClass.blockSize); i++) {
incrementCounterAt(ctr, 0);
keystreamBlocks.push(cipherClass.encrypt(ctr));
}
return xor(concatBytes(...keystreamBlocks), data);
};