Skip to content

PGP recipes ​

Complete scripts for the most common jobs. They share one set of names:

NameWhat it is
Secret pgp-private-keyYour private key, stored as one line of Base64
Secret pgp-passphraseThe passphrase of your private key
Secret partner-public-keyThe public key of your partner, stored the same way
Secret partner-fingerprintThe fingerprint of that key, confirmed with the partner
/data/keys/partner.ascThe public key of your partner, as a file

NOTE

These scripts require Syncplify Server! v8.12.0 or later.

Create your key ​

Run this once. It needs the secret pgp-passphrase to exist already, holding a long random passphrase.

ts
var passphrase = GetSecret("pgp-passphrase");
if (passphrase === "") {
  Log.Error("create the secret pgp-passphrase first");   // an empty passphrase would mean no protection
  Exit(1);
}

var key = PGPKey.Generate({ Name: "ACME Exports", Email: "pgp@acme.example", ExpiresDays: 730 });

if (key.SavePublic("/data/keys/acme.asc") && key.SavePrivate("/data/keys/acme.key", passphrase)) {
  Log.Info("key created, fingerprint " + key.Fingerprint + ", expires " + FormatDateTime("YYYY-MM-DD", key.Expires));
} else {
  Log.Error("the key files could not be written, see the log");
}

Then:

  1. Store acme.key as the secret pgp-private-key, encoded as one line of Base64.
  2. Send acme.asc to your partners, and confirm the fingerprint with them over another channel.
  3. Back up acme.key in a safe place, then remove it from the server.

Outbound: sign, encrypt, upload ​

ts
// The key of the partner: pinned, and watched for expiry
var partner = PGPKey.FromFile("/data/keys/partner.asc");
if (!partner.MatchesFingerprint(GetSecret("partner-fingerprint"))) {
  Log.Error("the partner key does not match the pinned fingerprint");
  Exit(1);
}
if (partner.Expires !== null && partner.Expires - new Date() < 30 * 86400000) {
  Log.Warn("the partner key expires on " + FormatDateTime("YYYY-MM-DD", partner.Expires));
}
var ours = PGPKey.FromSecret("pgp-private-key", "pgp-passphrase");

// Encrypt to the partner and to ourselves, sign, write binary output
var src = "/data/out/payroll.csv";
var enc = src + ".pgp";
if (!PGPEncryptFile(src, enc, [partner, ours], { SignWith: ours, Armor: false })) {
  Log.Error("encryption failed: " + PGPLastResult().ErrorMsg());
  Exit(1);
}

// Upload, and remove the plaintext only once the partner has the file
var cli = new SftpClient();
cli.Host          = "sftp.partner.example.com:22";
cli.User          = "acme";
cli.Pass          = GetSecret("sftp-pass");
cli.HostKeySHA256 = GetSecret("sftp-hostkey");
if (cli.Connect()) {
  if (cli.Upload(enc, "/inbox")) {
    SecureErase(src);
  } else {
    Log.Error("upload failed, " + src + " is kept");
  }
  cli.Close();
}

Inbound: accept only what the partner signed ​

ts
var ours    = PGPKey.FromSecret("pgp-private-key", "pgp-passphrase");
var partner = PGPKey.FromFile("/data/keys/partner.asc");

var files = ListDir("/data/in", "*.pgp");
for (var i = 0; i < files.length; i++) {
  var src = files[i].Name;                    // full path of the encrypted file
  var dst = src.replace(/\.pgp$/i, "");       // report.csv.pgp becomes report.csv
  if (PGPDecryptFile(src, dst, ours, { VerifyWith: partner })) {
    Log.Info("accepted " + dst + ", signed on " + FormatDateTime("YYYY-MM-DD HH:mm", PGPLastResult().SignedAt()));
    DelFile(src);
  } else {
    Log.Error("rejected " + src + ": " + PGPLastResult().ErrorMsg());
  }
}

A file that is not signed by the partner, or that was changed on the way, produces no output file at all.

Decrypt an upload in an event handler ​

This Syncplify Server! script belongs on the AfterFileUpload event. A client uploads orders.csv.pgp; the script leaves the decrypted orders.csv in its place, provided the partner signed it.

The uploaded file lives in a VFS, which may be a cloud bucket or a folder that is encrypted at rest. The script therefore exports it to a temporary local file, works on that, and imports the result. This works with every type of VFS.

ts
var rel = CtxRelPath();                              // for example /inbox/orders.csv.pgp
if (!/\.(pgp|gpg)$/i.test(rel)) {
  Exit();                                            // not an encrypted upload: nothing to do
}

var ours    = PGPKey.FromSecret("pgp-private-key", "pgp-passphrase");
var partner = PGPKey.FromSecret("partner-public-key");

var vfs    = GetCurrentVFS();
var target = rel.replace(/\.(pgp|gpg)$/i, "");       // /inbox/orders.csv
var encTmp = GetTempFileName();
var decTmp = GetTempFileName();

var exported = vfs.ExportFile(rel, encTmp);
if (!exported.Ok()) {
  Log.Error("cannot read " + rel + ": " + exported.ErrorMsg());
} else if (!PGPDecryptFile(encTmp, decTmp, ours, { VerifyWith: partner })) {
  Log.Error("rejected " + rel + ": " + PGPLastResult().ErrorMsg());
} else {
  var imported = vfs.ImportFile(decTmp, target);
  if (imported.Ok()) {
    vfs.Remove(rel);
    Log.Info("decrypted " + rel + " to " + target);
  } else {
    Log.Error("cannot store " + target + ": " + imported.ErrorMsg());
  }
}

// The temporary files hold the upload and its plaintext: always remove them
if (FileExists(encTmp)) { DelFile(encTmp); }
if (FileExists(decTmp)) { SecureErase(decTmp); }

Encrypt an upload in an event handler ​

The reverse job, on the same AfterFileUpload event: whatever a client uploads is replaced by a copy that only the partner can read, signed by you.

ts
var rel = CtxRelPath();                              // for example /outbox/invoice.pdf
if (/\.pgp$/i.test(rel)) {
  Exit();                                            // already encrypted
}

var partner = PGPKey.FromSecret("partner-public-key");
var ours    = PGPKey.FromSecret("pgp-private-key", "pgp-passphrase");

var vfs      = GetCurrentVFS();
var plainTmp = GetTempFileName();
var encTmp   = GetTempFileName();

// FileName stores the real name in the message, not the name of the temporary file
var options = { SignWith: ours, Armor: false, FileName: ExtractName(rel) };

var exported = vfs.ExportFile(rel, plainTmp);
if (!exported.Ok()) {
  Log.Error("cannot read " + rel + ": " + exported.ErrorMsg());
} else if (!PGPEncryptFile(plainTmp, encTmp, partner, options)) {
  Log.Error("cannot encrypt " + rel + ": " + PGPLastResult().ErrorMsg());
} else {
  var imported = vfs.ImportFile(encTmp, rel + ".pgp");
  if (imported.Ok()) {
    vfs.Remove(rel);
  } else {
    Log.Error("cannot store " + rel + ".pgp: " + imported.ErrorMsg());
  }
}

if (FileExists(plainTmp)) { SecureErase(plainTmp); }
if (FileExists(encTmp)) { DelFile(encTmp); }

TIP

PGP is the right tool for exchanging files with a partner. To protect the files your server stores, use a VFS that is encrypted at rest instead: it needs no script, and it encrypts and decrypts while the data is being transferred.