CipherSaber2.mjs 966 B

12345678910111213141516171819202122232425262728293031323334
  1. /**
  2. * @author n1073645 [n1073645@gmail.com]
  3. * @copyright Crown Copyright 2020
  4. * @license Apache-2.0
  5. */
  6. export function encode(tempIVP, key, rounds, input) {
  7. const ivp = new Uint8Array(key.concat(tempIVP));
  8. const state = new Array(256).fill(0);
  9. let j = 0, i = 0;
  10. const result = [];
  11. // Mixing states based off of IV.
  12. for (let i = 0; i < 256; i++)
  13. state[i] = i;
  14. const ivpLength = ivp.length;
  15. for (let r = 0; r < rounds; r ++) {
  16. for (let k = 0; k < 256; k++) {
  17. j = (j + state[k] + ivp[k % ivpLength]) % 256;
  18. [state[k], state[j]] = [state[j], state[k]];
  19. }
  20. }
  21. j = 0;
  22. i = 0;
  23. // XOR cipher with key.
  24. for (let x = 0; x < input.length; x++) {
  25. i = (++i) % 256;
  26. j = (j + state[i]) % 256;
  27. [state[i], state[j]] = [state[j], state[i]];
  28. const n = (state[i] + state[j]) % 256;
  29. result.push(state[n] ^ input[x]);
  30. }
  31. return result;
  32. }