BLAKE2s.mjs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /**
  2. * @author h345983745
  3. * @copyright Crown Copyright 2019
  4. * @license Apache-2.0
  5. */
  6. import Operation from "../Operation.mjs";
  7. import blakejs from "blakejs";
  8. import OperationError from "../errors/OperationError.mjs";
  9. import Utils from "../Utils.mjs";
  10. import { toBase64 } from "../lib/Base64.mjs";
  11. /**
  12. * BLAKE2s Operation
  13. */
  14. class BLAKE2s extends Operation {
  15. /**
  16. * BLAKE2s constructor
  17. */
  18. constructor() {
  19. super();
  20. this.name = "BLAKE2s";
  21. this.module = "Hashing";
  22. this.description = `Performs BLAKE2s hashing on the input.
  23. <br><br>BLAKE2s is a flavour of the BLAKE cryptographic hash function that is optimized for 8- to 32-bit platforms and produces digests of any size between 1 and 32 bytes.
  24. <br><br>Supports the use of an optional key.`;
  25. this.infoURL = "https://wikipedia.org/wiki/BLAKE_(hash_function)#BLAKE2";
  26. this.inputType = "ArrayBuffer";
  27. this.outputType = "string";
  28. this.args = [
  29. {
  30. "name": "Size",
  31. "type": "option",
  32. "value": ["256", "160", "128"]
  33. }, {
  34. "name": "Output Encoding",
  35. "type": "option",
  36. "value": ["Hex", "Base64", "Raw"]
  37. },
  38. {
  39. "name": "Key",
  40. "type": "toggleString",
  41. "value": "",
  42. "toggleValues": ["UTF8", "Decimal", "Base64", "Hex", "Latin1"]
  43. }
  44. ];
  45. }
  46. /**
  47. * @param {ArrayBuffer} input
  48. * @param {Object[]} args
  49. * @returns {string} The input having been hashed with BLAKE2s in the encoding format speicifed.
  50. */
  51. run(input, args) {
  52. const [outSize, outFormat] = args;
  53. let key = Utils.convertToByteArray(args[2].string || "", args[2].option);
  54. if (key.length === 0) {
  55. key = null;
  56. } else if (key.length > 32) {
  57. throw new OperationError(["Key cannot be greater than 32 bytes", "It is currently " + key.length + " bytes."].join("\n"));
  58. }
  59. input = new Uint8Array(input);
  60. switch (outFormat) {
  61. case "Hex":
  62. return blakejs.blake2sHex(input, key, outSize / 8);
  63. case "Base64":
  64. return toBase64(blakejs.blake2s(input, key, outSize / 8));
  65. case "Raw":
  66. return Utils.arrayBufferToStr(blakejs.blake2s(input, key, outSize / 8).buffer);
  67. default:
  68. return new OperationError("Unsupported Output Type");
  69. }
  70. }
  71. }
  72. export default BLAKE2s;