#:package Konscious.Security.Cryptography.Argon2@1.3.1 // Ephemer.pw — reference client for the public API (v1), in C#. // // Encrypts a secret locally, stores only the ciphertext on Ephemer and prints // a self-destructing link. The decryption key never leaves this machine // except inside the link you share (after the #). // // Run directly (.NET 10+, file-based app): // dotnet run Ephemer.cs -- --views 3 --expires 7d < secret.txt // EPHEMER_PASSPHRASE="…" dotnet run Ephemer.cs -- --passphrase < secret.txt // // Use as a library (.NET 8+): copy this file into your project, delete the // first line (#:package) and add the package instead: // dotnet add package Konscious.Security.Cryptography.Argon2 // (only used with a passphrase), then call EphemerClient.CreateSecretAsync. // In a project, also delete the "Command line" block at the end of the file. // // Protocol: https://ephemer.pw/developers · License: MIT #nullable enable using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Text.Json.Nodes; using Konscious.Security.Cryptography; // --------------------------------------------------------------------------- // Command line (file-based app only) // --------------------------------------------------------------------------- var views = 1; var expiresIn = "24h"; var api = "https://ephemer.pw"; string? passphrase = null; var positional = new List(); for (var i = 0; i < args.Length; i++) { switch (args[i]) { case "--views": views = int.Parse(args[++i]); break; case "--expires": expiresIn = args[++i]; break; case "--api": api = args[++i].TrimEnd('/'); break; case "--passphrase": passphrase = Environment.GetEnvironmentVariable("EPHEMER_PASSPHRASE"); if (string.IsNullOrEmpty(passphrase)) { Console.Error.WriteLine("ephemer: set EPHEMER_PASSPHRASE"); return 1; } break; default: positional.Add(args[i]); break; } } // Prefer stdin: a secret typed as an argument ends up in shell history. var text = positional.Count > 0 ? string.Join(" ", positional) : Console.IsInputRedirected ? await Console.In.ReadToEndAsync() : ""; try { var result = await EphemerClient.CreateSecretAsync( text, views, expiresIn, passphrase, api); Console.WriteLine(result.Url); Console.Error.WriteLine($"views: {result.ViewsLeft} · expires: {result.ExpiresAt:O}"); return 0; } catch (Exception error) { Console.Error.WriteLine($"ephemer: {error.Message}"); return 1; } // --------------------------------------------------------------------------- // Library // --------------------------------------------------------------------------- /// The JSON body of POST /api/v1/secrets, without views/expiresIn. public sealed record EncryptedPayload( string Id, string Ciphertext, string Iv, string Salt, string? AuthToken); /// Never send to the API: it is the key. public sealed record EncryptedSecret(string Id, string Fragment, EncryptedPayload Payload); public sealed record SharedSecret(string Url, DateTimeOffset ExpiresAt, int ViewsLeft); public static class EphemerClient { public static readonly string[] ExpiryOptions = ["5m", "30m", "1h", "12h", "24h", "3d", "7d"]; public const int MaxPlaintextBytes = 64 * 1024; const string IdAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-"; static readonly HttpClient Http = new(); /// Encrypts and stores a secret, returns the link to share. public static async Task CreateSecretAsync( string text, int views = 1, string expiresIn = "24h", string? passphrase = null, string api = "https://ephemer.pw", CancellationToken cancellationToken = default) { if (!ExpiryOptions.Contains(expiresIn)) throw new ArgumentException($"expiresIn must be one of {string.Join(", ", ExpiryOptions)}"); var secret = EncryptSecret(text, passphrase); // Built without reflection: works with trimming and Native AOT. var body = new JsonObject { ["id"] = secret.Payload.Id, ["ciphertext"] = secret.Payload.Ciphertext, ["iv"] = secret.Payload.Iv, ["salt"] = secret.Payload.Salt, ["authToken"] = secret.Payload.AuthToken, ["views"] = views, ["expiresIn"] = expiresIn, }; using var content = new StringContent(body.ToJsonString(), Encoding.UTF8, "application/json"); using var response = await Http.PostAsync($"{api}/api/v1/secrets", content, cancellationToken); using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync(cancellationToken)); var root = json.RootElement; if (!response.IsSuccessStatusCode) { var code = root.TryGetProperty("error", out var e) ? e.GetString() : "unknown_error"; throw new HttpRequestException($"HTTP {(int)response.StatusCode}: {code}"); } return new SharedSecret( $"{api}/s/{secret.Id}#{secret.Fragment}", root.GetProperty("expiresAt").GetDateTimeOffset(), root.GetProperty("viewsLeft").GetInt32()); } /// Encrypts locally. Nothing is sent anywhere. public static EncryptedSecret EncryptSecret(string text, string? passphrase = null) { var plaintext = Encoding.UTF8.GetBytes(text); if (plaintext.Length == 0) throw new ArgumentException("The secret is empty"); if (plaintext.Length > MaxPlaintextBytes) throw new ArgumentException($"The secret exceeds {MaxPlaintextBytes} bytes"); // 16 characters over a 64-symbol alphabet (96 bits); 256 % 64 == 0: unbiased. var id = new string(RandomNumberGenerator.GetBytes(16).Select(b => IdAlphabet[b & 63]).ToArray()); var salt = RandomNumberGenerator.GetBytes(16); var urlKey = RandomNumberGenerator.GetBytes(32); var iv = RandomNumberGenerator.GetBytes(12); // ikm = Argon2id(passphrase, salt) || urlKey — or urlKey alone var ikm = urlKey; if (!string.IsNullOrEmpty(passphrase)) { using var argon2 = new Argon2id(Encoding.UTF8.GetBytes(passphrase)) { Salt = salt, Iterations = 2, MemorySize = 19456, // KiB DegreeOfParallelism = 1, }; ikm = [.. argon2.GetBytes(32), .. urlKey]; } var contentKey = HKDF.DeriveKey(HashAlgorithmName.SHA256, ikm, 32, salt, Encoding.UTF8.GetBytes("ephemer:v1:content")); // The id is bound as additional authenticated data; the tag is appended. var ciphertext = new byte[plaintext.Length + 16]; using (var aes = new AesGcm(contentKey, tagSizeInBytes: 16)) { aes.Encrypt(iv, plaintext, ciphertext.AsSpan(0, plaintext.Length), ciphertext.AsSpan(plaintext.Length), Encoding.UTF8.GetBytes(id)); } string? authToken = null; if (!string.IsNullOrEmpty(passphrase)) { authToken = Base64Url(HKDF.DeriveKey(HashAlgorithmName.SHA256, ikm, 32, salt, Encoding.UTF8.GetBytes("ephemer:v1:auth"))); } return new EncryptedSecret(id, Base64Url(urlKey), new EncryptedPayload(id, Base64Url(ciphertext), Base64Url(iv), Base64Url(salt), authToken)); } static string Base64Url(byte[] bytes) => Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_'); }