ecdhes.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import { encoder, concat, uint32be, lengthAndInput, concatKdf } from '../lib/buffer_utils.js';
  2. import crypto, { isCryptoKey } from './webcrypto.js';
  3. import { checkEncCryptoKey } from '../lib/crypto_key.js';
  4. import invalidKeyInput from '../lib/invalid_key_input.js';
  5. import { types } from './is_key_like.js';
  6. export async function deriveKey(publicKey, privateKey, algorithm, keyLength, apu = new Uint8Array(0), apv = new Uint8Array(0)) {
  7. if (!isCryptoKey(publicKey)) {
  8. throw new TypeError(invalidKeyInput(publicKey, ...types));
  9. }
  10. checkEncCryptoKey(publicKey, 'ECDH');
  11. if (!isCryptoKey(privateKey)) {
  12. throw new TypeError(invalidKeyInput(privateKey, ...types));
  13. }
  14. checkEncCryptoKey(privateKey, 'ECDH', 'deriveBits');
  15. const value = concat(lengthAndInput(encoder.encode(algorithm)), lengthAndInput(apu), lengthAndInput(apv), uint32be(keyLength));
  16. let length;
  17. if (publicKey.algorithm.name === 'X25519') {
  18. length = 256;
  19. }
  20. else if (publicKey.algorithm.name === 'X448') {
  21. length = 448;
  22. }
  23. else {
  24. length =
  25. Math.ceil(parseInt(publicKey.algorithm.namedCurve.substr(-3), 10) / 8) << 3;
  26. }
  27. const sharedSecret = new Uint8Array(await crypto.subtle.deriveBits({
  28. name: publicKey.algorithm.name,
  29. public: publicKey,
  30. }, privateKey, length));
  31. return concatKdf(sharedSecret, keyLength, value);
  32. }
  33. export async function generateEpk(key) {
  34. if (!isCryptoKey(key)) {
  35. throw new TypeError(invalidKeyInput(key, ...types));
  36. }
  37. return crypto.subtle.generateKey(key.algorithm, true, ['deriveBits']);
  38. }
  39. export function ecdhAllowed(key) {
  40. if (!isCryptoKey(key)) {
  41. throw new TypeError(invalidKeyInput(key, ...types));
  42. }
  43. return (['P-256', 'P-384', 'P-521'].includes(key.algorithm.namedCurve) ||
  44. key.algorithm.name === 'X25519' ||
  45. key.algorithm.name === 'X448');
  46. }