validateAsymmetricKey.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. const ASYMMETRIC_KEY_DETAILS_SUPPORTED = require('./asymmetricKeyDetailsSupported');
  2. const RSA_PSS_KEY_DETAILS_SUPPORTED = require('./rsaPssKeyDetailsSupported');
  3. const allowedAlgorithmsForKeys = {
  4. 'ec': ['ES256', 'ES384', 'ES512'],
  5. 'rsa': ['RS256', 'PS256', 'RS384', 'PS384', 'RS512', 'PS512'],
  6. 'rsa-pss': ['PS256', 'PS384', 'PS512']
  7. };
  8. const allowedCurves = {
  9. ES256: 'prime256v1',
  10. ES384: 'secp384r1',
  11. ES512: 'secp521r1',
  12. };
  13. module.exports = function(algorithm, key) {
  14. if (!algorithm || !key) return;
  15. const keyType = key.asymmetricKeyType;
  16. if (!keyType) return;
  17. const allowedAlgorithms = allowedAlgorithmsForKeys[keyType];
  18. if (!allowedAlgorithms) {
  19. throw new Error(`Unknown key type "${keyType}".`);
  20. }
  21. if (!allowedAlgorithms.includes(algorithm)) {
  22. throw new Error(`"alg" parameter for "${keyType}" key type must be one of: ${allowedAlgorithms.join(', ')}.`)
  23. }
  24. /*
  25. * Ignore the next block from test coverage because it gets executed
  26. * conditionally depending on the Node version. Not ignoring it would
  27. * prevent us from reaching the target % of coverage for versions of
  28. * Node under 15.7.0.
  29. */
  30. /* istanbul ignore next */
  31. if (ASYMMETRIC_KEY_DETAILS_SUPPORTED) {
  32. switch (keyType) {
  33. case 'ec':
  34. const keyCurve = key.asymmetricKeyDetails.namedCurve;
  35. const allowedCurve = allowedCurves[algorithm];
  36. if (keyCurve !== allowedCurve) {
  37. throw new Error(`"alg" parameter "${algorithm}" requires curve "${allowedCurve}".`);
  38. }
  39. break;
  40. case 'rsa-pss':
  41. if (RSA_PSS_KEY_DETAILS_SUPPORTED) {
  42. const length = parseInt(algorithm.slice(-3), 10);
  43. const { hashAlgorithm, mgf1HashAlgorithm, saltLength } = key.asymmetricKeyDetails;
  44. if (hashAlgorithm !== `sha${length}` || mgf1HashAlgorithm !== hashAlgorithm) {
  45. throw new Error(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${algorithm}.`);
  46. }
  47. if (saltLength !== undefined && saltLength > length >> 3) {
  48. throw new Error(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${algorithm}.`)
  49. }
  50. }
  51. break;
  52. }
  53. }
  54. }