AccessTokenEncryptor.js 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. const { promisify } = require('util')
  2. const crypto = require('crypto')
  3. const ALGORITHM = 'aes-256-ctr'
  4. const cryptoHkdf = promisify(crypto.hkdf)
  5. const cryptoRandomBytes = promisify(crypto.randomBytes)
  6. class AbstractAccessTokenScheme {
  7. constructor(cipherLabel, cipherPassword) {
  8. this.cipherLabel = cipherLabel
  9. this.cipherPassword = cipherPassword
  10. }
  11. /**
  12. * @param {Object} json
  13. * @return {Promise<string>}
  14. */
  15. async encryptJson(json) {
  16. throw new Error('encryptJson is not implemented')
  17. }
  18. /**
  19. * @param {string} encryptedJson
  20. * @return {Promise<Object>}
  21. */
  22. async decryptToJson(encryptedJson) {
  23. throw new Error('decryptToJson is not implemented')
  24. }
  25. }
  26. class AccessTokenSchemeWithGenericKeyFn extends AbstractAccessTokenScheme {
  27. /**
  28. * @param {Buffer} salt
  29. * @return {Promise<Buffer>}
  30. */
  31. async keyFn(salt) {
  32. throw new Error('keyFn is not implemented')
  33. }
  34. async encryptJson(json) {
  35. const plainText = JSON.stringify(json)
  36. const bytes = await cryptoRandomBytes(32)
  37. const salt = bytes.slice(0, 16)
  38. const iv = bytes.slice(16, 32)
  39. const key = await this.keyFn(salt)
  40. const cipher = crypto.createCipheriv(ALGORITHM, key, iv)
  41. const cipherText =
  42. cipher.update(plainText, 'utf8', 'base64') + cipher.final('base64')
  43. return [
  44. this.cipherLabel,
  45. salt.toString('hex'),
  46. cipherText,
  47. iv.toString('hex'),
  48. ].join(':')
  49. }
  50. async decryptToJson(encryptedJson) {
  51. const [, salt, cipherText, iv] = encryptedJson.split(':', 4)
  52. const key = await this.keyFn(Buffer.from(salt, 'hex'))
  53. const decipher = crypto.createDecipheriv(
  54. ALGORITHM,
  55. key,
  56. Buffer.from(iv, 'hex')
  57. )
  58. const plainText =
  59. decipher.update(cipherText, 'base64', 'utf8') + decipher.final('utf8')
  60. try {
  61. return JSON.parse(plainText)
  62. } catch (e) {
  63. throw new Error('error decrypting token')
  64. }
  65. }
  66. }
  67. class AccessTokenSchemeV3 extends AccessTokenSchemeWithGenericKeyFn {
  68. async keyFn(salt) {
  69. const optionalInfo = ''
  70. return cryptoHkdf('sha512', this.cipherPassword, salt, optionalInfo, 32)
  71. }
  72. }
  73. class AccessTokenEncryptor {
  74. constructor(settings) {
  75. this.schemeByCipherLabel = new Map()
  76. for (const cipherLabel of Object.keys(settings.cipherPasswords)) {
  77. if (!cipherLabel) {
  78. throw new Error('cipherLabel cannot be empty')
  79. }
  80. if (cipherLabel.match(/:/)) {
  81. throw new Error(
  82. `cipherLabel must not contain a colon (:), got ${cipherLabel}`
  83. )
  84. }
  85. const [, version] = cipherLabel.split('-')
  86. if (!version) {
  87. throw new Error(
  88. `cipherLabel must contain version suffix (e.g. 2042.1-v42), got ${cipherLabel}`
  89. )
  90. }
  91. const cipherPassword = settings.cipherPasswords[cipherLabel]
  92. if (!cipherPassword) {
  93. throw new Error(`cipherPasswords['${cipherLabel}'] is missing`)
  94. }
  95. if (cipherPassword.length < 16) {
  96. throw new Error(`cipherPasswords['${cipherLabel}'] is too short`)
  97. }
  98. let scheme
  99. switch (version) {
  100. case 'v3':
  101. scheme = new AccessTokenSchemeV3(cipherLabel, cipherPassword)
  102. break
  103. default:
  104. throw new Error(`unknown version '${version}' for ${cipherLabel}`)
  105. }
  106. this.schemeByCipherLabel.set(cipherLabel, scheme)
  107. }
  108. this.defaultScheme = this.schemeByCipherLabel.get(settings.cipherLabel)
  109. if (!this.defaultScheme) {
  110. throw new Error(`unknown default cipherLabel ${settings.cipherLabel}`)
  111. }
  112. }
  113. encryptJson(json, callback) {
  114. this.defaultScheme.encryptJson(json).then(s => callback(null, s), callback)
  115. }
  116. decryptToJson(encryptedJson, callback) {
  117. const [label] = encryptedJson.split(':', 1)
  118. const scheme = this.schemeByCipherLabel.get(label)
  119. if (!scheme) {
  120. return callback(
  121. new Error('unknown access-token-encryptor label ' + label)
  122. )
  123. }
  124. scheme.decryptToJson(encryptedJson).then(o => callback(null, o), callback)
  125. }
  126. }
  127. module.exports = AccessTokenEncryptor