HMAC.mjs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /**
  2. * @author n1474335 [n1474335@gmail.com]
  3. * @copyright Crown Copyright 2016
  4. * @license Apache-2.0
  5. */
  6. import Operation from "../Operation";
  7. import Utils from "../Utils";
  8. import CryptoApi from "crypto-api/src/crypto-api";
  9. /**
  10. * HMAC operation
  11. */
  12. class HMAC extends Operation {
  13. /**
  14. * HMAC constructor
  15. */
  16. constructor() {
  17. super();
  18. this.name = "HMAC";
  19. this.module = "Hashing";
  20. this.description = "Keyed-Hash Message Authentication Codes (HMAC) are a mechanism for message authentication using cryptographic hash functions.";
  21. this.infoURL = "https://wikipedia.org/wiki/HMAC";
  22. this.inputType = "ArrayBuffer";
  23. this.outputType = "string";
  24. this.args = [
  25. {
  26. "name": "Key",
  27. "type": "toggleString",
  28. "value": "",
  29. "toggleValues": ["Hex", "Decimal", "Base64", "UTF8", "Latin1"]
  30. },
  31. {
  32. "name": "Hashing function",
  33. "type": "option",
  34. "value": [
  35. "MD2",
  36. "MD4",
  37. "MD5",
  38. "SHA0",
  39. "SHA1",
  40. "SHA224",
  41. "SHA256",
  42. "SHA384",
  43. "SHA512",
  44. "SHA512/224",
  45. "SHA512/256",
  46. "RIPEMD128",
  47. "RIPEMD160",
  48. "RIPEMD256",
  49. "RIPEMD320",
  50. "HAS160",
  51. "Whirlpool",
  52. "Whirlpool-0",
  53. "Whirlpool-T",
  54. "Snefru"
  55. ]
  56. }
  57. ];
  58. }
  59. /**
  60. * @param {ArrayBuffer} input
  61. * @param {Object[]} args
  62. * @returns {string}
  63. */
  64. run(input, args) {
  65. const key = Utils.convertToByteString(args[0].string || "", args[0].option),
  66. hashFunc = args[1].toLowerCase(),
  67. msg = Utils.arrayBufferToStr(input, false),
  68. hasher = CryptoApi.getHasher(hashFunc);
  69. const mac = CryptoApi.getHmac(CryptoApi.encoder.fromUtf(key), hasher);
  70. mac.update(msg);
  71. return CryptoApi.encoder.toHex(mac.finalize());
  72. }
  73. }
  74. export default HMAC;