pad.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. * pkcs7.pad
  3. * https://github.com/brightcove/pkcs7
  4. *
  5. * Copyright (c) 2014 Brightcove
  6. * Licensed under the apache2 license.
  7. */
  8. 'use strict';
  9. var PADDING;
  10. /**
  11. * Returns a new Uint8Array that is padded with PKCS#7 padding.
  12. * @param plaintext {Uint8Array} the input bytes before encryption
  13. * @return {Uint8Array} the padded bytes
  14. * @see http://tools.ietf.org/html/rfc5652
  15. */
  16. module.exports = function pad(plaintext) {
  17. var padding = PADDING[(plaintext.byteLength % 16) || 0],
  18. result = new Uint8Array(plaintext.byteLength + padding.length);
  19. result.set(plaintext);
  20. result.set(padding, plaintext.byteLength);
  21. return result;
  22. };
  23. // pre-define the padding values
  24. PADDING = [
  25. [16, 16, 16, 16,
  26. 16, 16, 16, 16,
  27. 16, 16, 16, 16,
  28. 16, 16, 16, 16],
  29. [15, 15, 15, 15,
  30. 15, 15, 15, 15,
  31. 15, 15, 15, 15,
  32. 15, 15, 15],
  33. [14, 14, 14, 14,
  34. 14, 14, 14, 14,
  35. 14, 14, 14, 14,
  36. 14, 14],
  37. [13, 13, 13, 13,
  38. 13, 13, 13, 13,
  39. 13, 13, 13, 13,
  40. 13],
  41. [12, 12, 12, 12,
  42. 12, 12, 12, 12,
  43. 12, 12, 12, 12],
  44. [11, 11, 11, 11,
  45. 11, 11, 11, 11,
  46. 11, 11, 11],
  47. [10, 10, 10, 10,
  48. 10, 10, 10, 10,
  49. 10, 10],
  50. [9, 9, 9, 9,
  51. 9, 9, 9, 9,
  52. 9],
  53. [8, 8, 8, 8,
  54. 8, 8, 8, 8],
  55. [7, 7, 7, 7,
  56. 7, 7, 7],
  57. [6, 6, 6, 6,
  58. 6, 6],
  59. [5, 5, 5, 5,
  60. 5],
  61. [4, 4, 4, 4],
  62. [3, 3, 3],
  63. [2, 2],
  64. [1]
  65. ];