Ciphers.mjs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /**
  2. * Cipher functions.
  3. *
  4. * @author Matt C [matt@artemisbot.uk]
  5. * @author n1474335 [n1474335@gmail.com]
  6. *
  7. * @copyright Crown Copyright 2018
  8. * @license Apache-2.0
  9. *
  10. */
  11. import OperationError from "../errors/OperationError.mjs";
  12. import CryptoJS from "crypto-js";
  13. /**
  14. * Affine Cipher Encode operation.
  15. *
  16. * @author Matt C [matt@artemisbot.uk]
  17. * @param {string} input
  18. * @param {Object[]} args
  19. * @returns {string}
  20. */
  21. export function affineEncode(input, args) {
  22. const alphabet = "abcdefghijklmnopqrstuvwxyz",
  23. a = args[0],
  24. b = args[1];
  25. let output = "";
  26. if (!/^\+?(0|[1-9]\d*)$/.test(a) || !/^\+?(0|[1-9]\d*)$/.test(b)) {
  27. throw new OperationError("The values of a and b can only be integers.");
  28. }
  29. for (let i = 0; i < input.length; i++) {
  30. if (alphabet.indexOf(input[i]) >= 0) {
  31. // Uses the affine function ax+b % m = y (where m is length of the alphabet)
  32. output += alphabet[((a * alphabet.indexOf(input[i])) + b) % 26];
  33. } else if (alphabet.indexOf(input[i].toLowerCase()) >= 0) {
  34. // Same as above, accounting for uppercase
  35. output += alphabet[((a * alphabet.indexOf(input[i].toLowerCase())) + b) % 26].toUpperCase();
  36. } else {
  37. // Non-alphabetic characters
  38. output += input[i];
  39. }
  40. }
  41. return output;
  42. }
  43. /**
  44. * Generates a polybius square for the given keyword
  45. *
  46. * @private
  47. * @author Matt C [matt@artemisbot.uk]
  48. * @param {string} keyword - Must be upper case
  49. * @returns {string}
  50. */
  51. export function genPolybiusSquare (keyword) {
  52. const alpha = "ABCDEFGHIKLMNOPQRSTUVWXYZ",
  53. polArray = `${keyword}${alpha}`.split("").unique(),
  54. polybius = [];
  55. for (let i = 0; i < 5; i++) {
  56. polybius[i] = polArray.slice(i*5, i*5 + 5);
  57. }
  58. return polybius;
  59. }
  60. /**
  61. * A mapping of string formats to their classes in the CryptoJS library.
  62. *
  63. * @private
  64. * @constant
  65. */
  66. export const format = {
  67. "Hex": CryptoJS.enc.Hex,
  68. "Base64": CryptoJS.enc.Base64,
  69. "UTF8": CryptoJS.enc.Utf8,
  70. "UTF16": CryptoJS.enc.Utf16,
  71. "UTF16LE": CryptoJS.enc.Utf16LE,
  72. "UTF16BE": CryptoJS.enc.Utf16BE,
  73. "Latin1": CryptoJS.enc.Latin1,
  74. };