Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

crypto-utils.js 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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-CTR',
  19. length: 128
  20. }, false, [ 'encrypt', 'decrypt' ]);
  21. const authenticationKey = await crypto.subtle.deriveKey({
  22. name: 'HKDF',
  23. salt: textEncoder.encode('JFrameAuthenticationKey'),
  24. hash: 'SHA-256',
  25. info
  26. }, material, {
  27. name: 'HMAC',
  28. hash: 'SHA-256'
  29. }, false, [ 'sign' ]);
  30. const saltKey = await crypto.subtle.deriveBits({
  31. name: 'HKDF',
  32. salt: textEncoder.encode('JFrameSaltKey'),
  33. hash: 'SHA-256',
  34. info
  35. }, material, 128);
  36. return {
  37. material,
  38. encryptionKey,
  39. authenticationKey,
  40. saltKey
  41. };
  42. }
  43. /**
  44. * Ratchets a key. See
  45. * https://tools.ietf.org/html/draft-omara-sframe-00#section-4.3.5.1
  46. * @param {CryptoKey} material - base key material
  47. * @returns {ArrayBuffer} - ratcheted key material
  48. */
  49. export async function ratchet(material) {
  50. const textEncoder = new TextEncoder();
  51. // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/deriveBits
  52. return crypto.subtle.deriveBits({
  53. name: 'HKDF',
  54. salt: textEncoder.encode('JFrameRatchetKey'),
  55. hash: 'SHA-256',
  56. info: new ArrayBuffer()
  57. }, material, 256);
  58. }
  59. /**
  60. * Converts a raw key into a WebCrypto key object with default options
  61. * suitable for our usage.
  62. * @param {ArrayBuffer} keyBytes - raw key
  63. * @param {Array} keyUsages - key usages, see importKey documentation
  64. * @returns {CryptoKey} - the WebCrypto key.
  65. */
  66. export async function importKey(keyBytes) {
  67. // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey
  68. return crypto.subtle.importKey('raw', keyBytes, 'HKDF', false, [ 'deriveBits', 'deriveKey' ]);
  69. }