Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

crypto-utils.js 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /**
  2. * Derives a set of keys from the master key.
  3. * @param {CryptoKey} material - master key to derive from
  4. *
  5. * See https://tools.ietf.org/html/draft-omara-sframe-00#section-4.3.1
  6. */
  7. export async function deriveKeys(material) {
  8. const info = new ArrayBuffer();
  9. const textEncoder = new TextEncoder();
  10. // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/deriveKey#HKDF
  11. // https://developer.mozilla.org/en-US/docs/Web/API/HkdfParams
  12. const encryptionKey = await crypto.subtle.deriveKey({
  13. name: 'HKDF',
  14. salt: textEncoder.encode('JFrameEncryptionKey'),
  15. hash: 'SHA-256',
  16. info
  17. }, material, {
  18. name: 'AES-GCM',
  19. length: 128
  20. }, false, [ 'encrypt', 'decrypt' ]);
  21. return {
  22. material,
  23. encryptionKey
  24. };
  25. }
  26. /**
  27. * Ratchets a key. See
  28. * https://tools.ietf.org/html/draft-omara-sframe-00#section-4.3.5.1
  29. * @param {CryptoKey} material - base key material
  30. * @returns {Promise<ArrayBuffer>} - ratcheted key material
  31. */
  32. export async function ratchet(material) {
  33. const textEncoder = new TextEncoder();
  34. // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/deriveBits
  35. return crypto.subtle.deriveBits({
  36. name: 'HKDF',
  37. salt: textEncoder.encode('JFrameRatchetKey'),
  38. hash: 'SHA-256',
  39. info: new ArrayBuffer()
  40. }, material, 256);
  41. }
  42. /**
  43. * Converts a raw key into a WebCrypto key object with default options
  44. * suitable for our usage.
  45. * @param {ArrayBuffer} keyBytes - raw key
  46. * @param {Array} keyUsages - key usages, see importKey documentation
  47. * @returns {Promise<CryptoKey>} - the WebCrypto key.
  48. */
  49. export async function importKey(keyBytes) {
  50. // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey
  51. return crypto.subtle.importKey('raw', keyBytes, 'HKDF', false, [ 'deriveBits', 'deriveKey' ]);
  52. }