ecdhes.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { encode, concat, uint32be } from './buffer_utils.js';
  2. import { checkEncCryptoKey } from './crypto_key.js';
  3. import { digest } from './helpers.js';
  4. function lengthAndInput(input) {
  5. return concat(uint32be(input.length), input);
  6. }
  7. async function concatKdf(Z, L, OtherInfo) {
  8. const dkLen = L >> 3;
  9. const hashLen = 32;
  10. const reps = Math.ceil(dkLen / hashLen);
  11. const dk = new Uint8Array(reps * hashLen);
  12. for (let i = 1; i <= reps; i++) {
  13. const hashInput = new Uint8Array(4 + Z.length + OtherInfo.length);
  14. hashInput.set(uint32be(i), 0);
  15. hashInput.set(Z, 4);
  16. hashInput.set(OtherInfo, 4 + Z.length);
  17. const hashResult = await digest('sha256', hashInput);
  18. dk.set(hashResult, (i - 1) * hashLen);
  19. }
  20. return dk.slice(0, dkLen);
  21. }
  22. export async function deriveKey(publicKey, privateKey, algorithm, keyLength, apu = new Uint8Array(), apv = new Uint8Array()) {
  23. checkEncCryptoKey(publicKey, 'ECDH');
  24. checkEncCryptoKey(privateKey, 'ECDH', 'deriveBits');
  25. const algorithmID = lengthAndInput(encode(algorithm));
  26. const partyUInfo = lengthAndInput(apu);
  27. const partyVInfo = lengthAndInput(apv);
  28. const suppPubInfo = uint32be(keyLength);
  29. const suppPrivInfo = new Uint8Array();
  30. const otherInfo = concat(algorithmID, partyUInfo, partyVInfo, suppPubInfo, suppPrivInfo);
  31. const Z = new Uint8Array(await crypto.subtle.deriveBits({
  32. name: publicKey.algorithm.name,
  33. public: publicKey,
  34. }, privateKey, getEcdhBitLength(publicKey)));
  35. return concatKdf(Z, keyLength, otherInfo);
  36. }
  37. function getEcdhBitLength(publicKey) {
  38. if (publicKey.algorithm.name === 'X25519') {
  39. return 256;
  40. }
  41. return (Math.ceil(parseInt(publicKey.algorithm.namedCurve.slice(-3), 10) / 8) << 3);
  42. }
  43. export function allowed(key) {
  44. switch (key.algorithm.namedCurve) {
  45. case 'P-256':
  46. case 'P-384':
  47. case 'P-521':
  48. return true;
  49. default:
  50. return key.algorithm.name === 'X25519';
  51. }
  52. }