encryption-helper.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. 'use strict';
  2. const crypto = require('crypto');
  3. const ece = require('http_ece');
  4. const encrypt = function(userPublicKey, userAuth, payload, contentEncoding) {
  5. if (!userPublicKey) {
  6. throw new Error('No user public key provided for encryption.');
  7. }
  8. if (typeof userPublicKey !== 'string') {
  9. throw new Error('The subscription p256dh value must be a string.');
  10. }
  11. if (Buffer.from(userPublicKey, 'base64url').length !== 65) {
  12. throw new Error('The subscription p256dh value should be 65 bytes long.');
  13. }
  14. if (!userAuth) {
  15. throw new Error('No user auth provided for encryption.');
  16. }
  17. if (typeof userAuth !== 'string') {
  18. throw new Error('The subscription auth key must be a string.');
  19. }
  20. if (Buffer.from(userAuth, 'base64url').length < 16) {
  21. throw new Error('The subscription auth key should be at least 16 '
  22. + 'bytes long');
  23. }
  24. if (typeof payload !== 'string' && !Buffer.isBuffer(payload)) {
  25. throw new Error('Payload must be either a string or a Node Buffer.');
  26. }
  27. if (typeof payload === 'string' || payload instanceof String) {
  28. payload = Buffer.from(payload);
  29. }
  30. const localCurve = crypto.createECDH('prime256v1');
  31. const localPublicKey = localCurve.generateKeys();
  32. const salt = crypto.randomBytes(16).toString('base64url');
  33. const cipherText = ece.encrypt(payload, {
  34. version: contentEncoding,
  35. dh: userPublicKey,
  36. privateKey: localCurve,
  37. salt: salt,
  38. authSecret: userAuth
  39. });
  40. return {
  41. localPublicKey: localPublicKey,
  42. salt: salt,
  43. cipherText: cipherText
  44. };
  45. };
  46. module.exports = {
  47. encrypt: encrypt
  48. };