BaconCipherEncode.mjs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /**
  2. * @author Karsten Silkenbäumer [github.com/kassi]
  3. * @copyright Karsten Silkenbäumer 2019
  4. * @license Apache-2.0
  5. */
  6. import Operation from "../Operation.mjs";
  7. import {
  8. BACON_ALPHABETS,
  9. BACON_TRANSLATIONS_FOR_ENCODING, BACON_TRANSLATION_AB,
  10. swapZeroAndOne
  11. } from "../lib/Bacon.mjs";
  12. /**
  13. * Bacon Cipher Encode operation
  14. */
  15. class BaconCipherEncode extends Operation {
  16. /**
  17. * BaconCipherEncode constructor
  18. */
  19. constructor() {
  20. super();
  21. this.name = "Bacon Cipher Encode";
  22. this.module = "Default";
  23. this.description = "Bacon's cipher or the Baconian cipher is a method of steganography devised by Francis Bacon in 1605. A message is concealed in the presentation of text, rather than its content.";
  24. this.infoURL = "https://wikipedia.org/wiki/Bacon%27s_cipher";
  25. this.inputType = "string";
  26. this.outputType = "string";
  27. this.args = [
  28. {
  29. "name": "Alphabet",
  30. "type": "option",
  31. "value": Object.keys(BACON_ALPHABETS)
  32. },
  33. {
  34. "name": "Translation",
  35. "type": "option",
  36. "value": BACON_TRANSLATIONS_FOR_ENCODING
  37. },
  38. {
  39. "name": "Keep extra characters",
  40. "type": "boolean",
  41. "value": false
  42. },
  43. {
  44. "name": "Invert Translation",
  45. "type": "boolean",
  46. "value": false
  47. }
  48. ];
  49. }
  50. /**
  51. * @param {string} input
  52. * @param {Object[]} args
  53. * @returns {string}
  54. */
  55. run(input, args) {
  56. const [alphabet, translation, keep, invert] = args;
  57. const alphabetObject = BACON_ALPHABETS[alphabet];
  58. const charCodeA = "A".charCodeAt(0);
  59. const charCodeZ = "Z".charCodeAt(0);
  60. let output = input.replace(/./g, function (c) {
  61. const charCode = c.toUpperCase().charCodeAt(0);
  62. if (charCode >= charCodeA && charCode <= charCodeZ) {
  63. let code = charCode - charCodeA;
  64. if (alphabetObject.codes !== undefined) {
  65. code = alphabetObject.codes[code];
  66. }
  67. const bacon = ("00000" + code.toString(2)).substr(-5, 5);
  68. return bacon;
  69. } else {
  70. return c;
  71. }
  72. });
  73. if (invert) {
  74. output = swapZeroAndOne(output);
  75. }
  76. if (!keep) {
  77. output = output.replace(/[^01]/g, "");
  78. const outputArray = output.match(/(.{5})/g) || [];
  79. output = outputArray.join(" ");
  80. }
  81. if (translation === BACON_TRANSLATION_AB) {
  82. output = output.replace(/[01]/g, function (c) {
  83. return {
  84. "0": "A",
  85. "1": "B"
  86. }[c];
  87. });
  88. }
  89. return output;
  90. }
  91. }
  92. export default BaconCipherEncode;