Skip to content

Sync-in · Sovereign platform for file storage, sharing, synchronization, and collaboration.

1.5 KB
Raw Blame
import crypto from 'crypto'

// Encrypt a plaintext string with a passphrase. Returns a compact string.
export function encryptSecret(plaintext: string, passphrase: string) {
  const salt = crypto.randomBytes(16) // for key derivation (scrypt)
  const iv = crypto.randomBytes(12) // recommended IV length for GCM
  const key = crypto.scryptSync(passphrase, salt, 32)

  const cipher = crypto.createCipheriv('aes-256-gcm', key, iv)
  const ciphertext = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()])
  const tag = cipher.getAuthTag()

  // Encode everything in base64 and concatenate: salt.iv.tag.cipher
  return [salt.toString('base64'), iv.toString('base64'), tag.toString('base64'), ciphertext.toString('base64')].join('.')
}

// Decrypt the string generated by encryptSecret with the same passphrase.
export function decryptSecret(payload: string, passphrase: string) {
  const [saltB64, ivB64, tagB64, ctB64] = payload.split('.')
  if (!saltB64 || !ivB64 || !tagB64 || !ctB64) {
    throw new Error('Invalid payload format')
  }

  const salt = Buffer.from(saltB64, 'base64')
  const iv = Buffer.from(ivB64, 'base64')
  const tag = Buffer.from(tagB64, 'base64')
  const ct = Buffer.from(ctB64, 'base64')

  const key = crypto.scryptSync(passphrase, salt, 32)
  const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv)
  decipher.setAuthTag(tag)

  const plaintext = Buffer.concat([decipher.update(ct), decipher.final()])
  return plaintext.toString('utf8')
}