Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions ports/csharp/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
bin/
obj/
build/
hello.png
examples/**/bin/
examples/**/obj/
12 changes: 12 additions & 0 deletions ports/csharp/Prism.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,12 @@

namespace PrismCode
{
/// <summary>Code mode: 8-color or black-and-white.</summary>
public enum PrismMode { Color = 0, BW = 1 }
/// <summary>Payload type stored in the code header.</summary>
public enum PrismType { Text = 0, Binary = 1 }

/// <summary>Thrown on any encode/decode failure; the message is a human-readable reason.</summary>
public class PrismException : Exception
{
public PrismException(string message) : base(message) { }
Expand All @@ -27,6 +30,8 @@ public sealed class PrismDecodeResult
public int Type, Size, Ecc, Mode;
}

/// <summary>Comb Code encoder and clean-image decoder, byte-exact with the live JavaScript.
/// A decode only returns a payload when its header CRC and payload CRC-32 pass.</summary>
public static class Comb
{
/* -------------------------------------------------------- constants */
Expand Down Expand Up @@ -177,6 +182,7 @@ private static int RsDecode(byte[] r, int nsym)
}

/* ------------------------------------------------------------ CRC */
/// <summary>CRC-32 (IEEE) of the first <paramref name="len"/> bytes.</summary>
public static uint Crc32(byte[] bytes, int len)
{
uint c = 0xFFFFFFFFu;
Expand Down Expand Up @@ -297,6 +303,7 @@ private static Capacity CapacityOf(int size, int ecc, int mode)
}

/// <summary>Maximum payload bytes for a size (0..5), ecc (0..3) and mode.</summary>
/// <summary>Maximum payload bytes for a size (0..5), repair level (0..3 = 10/20/30/40%) and mode.</summary>
public static int CapacityPayload(int size, int ecc, PrismMode mode) =>
CapacityOf(size, ecc, (int)mode).Payload;

Expand Down Expand Up @@ -393,6 +400,8 @@ private static Code EncodeCode(byte[] bytes, int size, int ecc, int mode, int ty

/* ----------------------------------------------------------- render */
/// <summary>Encode payload bytes to an in-memory RGBA image.</summary>
/// <summary>Encode payload bytes to an in-memory image. <paramref name="size"/> -1 = automatic
/// or 0..5; <paramref name="ecc"/> 0..3; <paramref name="scale"/> pixels per cell unit (live default 12).</summary>
public static PrismImage Encode(byte[] payload, int size = -1, int ecc = 1,
PrismMode mode = PrismMode.Color, PrismType type = PrismType.Text,
int scale = 12)
Expand Down Expand Up @@ -452,6 +461,7 @@ public static PrismImage Encode(byte[] payload, int size = -1, int ecc = 1,
}

/// <summary>Encode and write a PNG file.</summary>
/// <summary>Encode payload bytes and write a PNG file.</summary>
public static void EncodePng(byte[] payload, string path, int size = -1, int ecc = 1,
PrismMode mode = PrismMode.Color, PrismType type = PrismType.Text,
int scale = 12) =>
Expand Down Expand Up @@ -572,6 +582,8 @@ private static PrismDecodeResult DecodeSized(PrismImage img, int size, double r)
/// Decode a Comb code from a clean PNG (encoder output; not the robust
/// camera pipeline). CRC32 verified. Throws PrismException on failure.
/// </summary>
/// <summary>Decode a clean PNG produced by an encoder. For the phone-camera pipeline
/// (glare, blur, perspective) see the reader project in reader/.</summary>
public static PrismDecodeResult DecodePng(string path)
{
var img = Png.Read(path);
Expand Down
12 changes: 12 additions & 0 deletions ports/csharp/PrismCards.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

namespace PrismCode
{
/// <summary>Parsed Wi-Fi card fields (WIFI: payload).</summary>
public sealed class WifiCard
{
public string Ssid = "";
Expand All @@ -16,12 +17,14 @@ public sealed class WifiCard
public bool Hidden;
}

/// <summary>Parsed contact-card fields (vCard 3.0 payload).</summary>
public sealed class VCard
{
public string Name = "", Org = "", Title = "", Addr = "", Note = "";
public List<string> Phones = new(), Emails = new(), Urls = new();
}

/// <summary>Parsed expiring-ticket fields (PRISM-TICKET/1 payload).</summary>
public sealed class TicketCard
{
public long ExpiryMs;
Expand All @@ -30,12 +33,15 @@ public sealed class TicketCard

public enum CardKind { None, Ticket, Wifi, VCard }

/// <summary>Builds and parses the site's Wi-Fi, vCard 3.0 contact-card and expiring-ticket
/// payloads, byte-identical to the live comb-cards.js (escaping included).</summary>
public static class PrismCards
{
/* ---------- Wi-Fi ---------- */

static string EscWifi(string s) => Regex.Replace(s, "([\\\\;,:\"'])", "\\$1");

/// <summary>Build a Wi-Fi payload (WIFI:S:...;T:...;P:...;H:...;;).</summary>
public static string WifiPayload(string ssid, string sec = "WPA", string pass = "", bool hidden = false)
{
string t = string.IsNullOrEmpty(sec) ? "WPA" : sec;
Expand All @@ -47,6 +53,7 @@ public static string WifiPayload(string ssid, string sec = "WPA", string pass =
return sb.ToString();
}

/// <summary>Parse a Wi-Fi payload.</summary>
public static bool TryParseWifi(string text, out WifiCard card)
{
card = null!;
Expand Down Expand Up @@ -91,6 +98,7 @@ void Push()

static string EscV(string s) => s.Replace("\\", "\\\\").Replace("\n", "\\n").Replace(",", "\\,").Replace(";", "\\;");

/// <summary>Build a vCard 3.0 contact-card payload.</summary>
public static string VCardPayload(string name, string org = "", string title = "",
string phone = "", string email = "", string url = "", string addr = "", string note = "")
{
Expand All @@ -116,6 +124,7 @@ public static string VCardPayload(string name, string org = "", string title = "
static string UnescV(string s) =>
Regex.Replace(s.Replace("\\n", "\n").Replace("\\N", "\n"), "\\\\([,;\\\\])", "$1");

/// <summary>Parse a vCard 3.0 contact-card payload.</summary>
public static bool TryParseVCard(string text, out VCard card)
{
card = null!;
Expand Down Expand Up @@ -148,9 +157,11 @@ string Get(string k)

/* ---------- ticket ---------- */

/// <summary>Build an expiring-ticket payload (expiry in milliseconds since the Unix epoch).</summary>
public static string TicketPayload(long expiryMs, string text) =>
"PRISM-TICKET/1\nEXP:" + (expiryMs / 1000) + "\n" + (text ?? "").Trim();

/// <summary>Parse an expiring-ticket payload.</summary>
public static bool TryParseTicket(string text, out TicketCard card)
{
card = null!;
Expand All @@ -161,6 +172,7 @@ public static bool TryParseTicket(string text, out TicketCard card)
return true;
}

/// <summary>Detect which card kind a decoded text payload holds.</summary>
public static CardKind Detect(string text)
{
if (string.IsNullOrEmpty(text)) return CardKind.None;
Expand Down
5 changes: 5 additions & 0 deletions ports/csharp/PrismIssuers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,13 @@ public sealed class Issuer
public string? Url { get; set; }
}

/// <summary>Ticket-issuer identities: recognize a signed ticket's issuer from its signing key
/// and match fingerprints against the site's issuers list (comb-issuers.js compatible).</summary>
public static class PrismIssuers
{
/* Inspect decoded payload bytes. Returns null for plain or unsigned
* payloads, else the identity. Read-only: never decrypts. */
/// <summary>Identify the issuer of a decoded, signed ticket payload; null when not a signed ticket.</summary>
public static IssuerIdentity? Identify(byte[] bytes)
{
if (bytes == null || bytes.Length < 5 + 65 + 64) return null;
Expand Down Expand Up @@ -65,6 +68,7 @@ public static class PrismIssuers
}

/* Loads an issuers.json file (empty list when missing or damaged). */
/// <summary>Load the site's issuers.json list.</summary>
public static List<Issuer> Load(string path)
{
try
Expand Down Expand Up @@ -93,6 +97,7 @@ static string Norm(string f)
return sb.ToString();
}

/// <summary>Find an issuer by XXXX-XXXX fingerprint.</summary>
public static Issuer? Find(IEnumerable<Issuer> issuers, string fingerprint)
{
string want = Norm(fingerprint);
Expand Down
15 changes: 14 additions & 1 deletion ports/csharp/PrismParts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@

namespace PrismCode
{
/// <summary>Split plan for a file: per-part payload room, part count and cleaned name.</summary>
public sealed class PartsPlan
{
public int Room;
public int Total;
public string Name = "";
}

/// <summary>Decoded PPT1 part: file id, position, whole-file length/CRC-32, name and chunk bytes.</summary>
public sealed class PartInfo
{
public string Id = "";
Expand All @@ -22,6 +24,8 @@ public sealed class PartInfo
public byte[] Chunk = Array.Empty<byte>();
}

/// <summary>Multi-part files (PPT1 payloads), byte-compatible with the live comb-parts.js.
/// Parts are encoded at 30% repair data, color mode.</summary>
public static class PrismParts
{
public const int PartsEcc = 2; // parts are encoded at 30% repair data, color mode
Expand Down Expand Up @@ -85,16 +89,18 @@ static byte[] NameBytes(string name)

static int Overhead(int nameLen) => 4 + 4 + 2 + 2 + 4 + 4 + 1 + nameLen + 4;

/// <summary>Compute the split plan for <paramref name="len"/> bytes at code size 2..5.</summary>
public static PartsPlan Plan(long len, string name, int codeSize)
{
byte[] nb = NameBytes(name);
int room = Prism.CapacityPayload(codeSize, PartsEcc, PrismMode.Color) - Overhead(nb.Length);
int room = Comb.CapacityPayload(codeSize, PartsEcc, PrismMode.Color) - Overhead(nb.Length);
if (room < 64) throw new InvalidOperationException("Part size too small");
long total = Math.Max(1, (len + room - 1) / room);
if (total > 65535) throw new InvalidOperationException("File is too big for this part size");
return new PartsPlan { Room = room, Total = (int)total, Name = Encoding.UTF8.GetString(nb) };
}

/// <summary>Split a file into PPT1 part payloads, ready to encode one code each.</summary>
public static byte[][] Split(byte[] bytes, string name, int codeSize)
{
var plan = Plan(bytes.Length, name, codeSize);
Expand Down Expand Up @@ -124,6 +130,8 @@ public static byte[][] Split(byte[] bytes, string name, int codeSize)
}

// ok: info set. notPart: not a part. bad: damaged part (site's message).
/// <summary>Parse one PPT1 payload. <paramref name="notPart"/> is true when the bytes are not a part at all;
/// <paramref name="bad"/> carries the reason for a damaged part.</summary>
public static bool TryParse(byte[] b, out PartInfo info, out bool notPart, out string bad)
{
info = null!; notPart = false; bad = null!;
Expand Down Expand Up @@ -152,13 +160,16 @@ public static bool TryParse(byte[] b, out PartInfo info, out bool notPart, out s

public enum PartAddStatus { NotPart, Bad, OtherFile, Duplicate, New, Complete }

/// <summary>Outcome of adding one part to a <see cref="PartsAssembler"/>, with the site's user-facing message.</summary>
public sealed class PartAddResult
{
public PartAddStatus Status;
public int N;
public string Message = "";
}

/// <summary>Reassembles a file from its parts in any order: detects duplicates, parts of another
/// file and damaged parts, and verifies the whole-file CRC-32.</summary>
public sealed class PartsAssembler
{
string _id = null!;
Expand All @@ -172,6 +183,7 @@ public sealed class PartsAssembler
public int Total => _total;
public string Name => _name;

/// <summary>Add one decoded part payload.</summary>
public PartAddResult Add(byte[] bytes)
{
if (!PrismParts.TryParse(bytes, out var p, out bool notPart, out string bad))
Expand All @@ -196,6 +208,7 @@ public PartAddResult Add(byte[] bytes)
return new PartAddResult { Status = _have == _total ? PartAddStatus.Complete : PartAddStatus.New, N = p.N };
}

/// <summary>Return the reassembled file once all parts are present; throws otherwise.</summary>
public byte[] Finish()
{
if (_have != _total) throw new InvalidOperationException("Parts are still missing.");
Expand Down
14 changes: 14 additions & 0 deletions ports/csharp/PrismSecure.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,14 @@

namespace PrismCode
{
/// <summary>An ECDSA P-256 signing key: raw 0x04|X|Y public key plus JWK private key.</summary>
public sealed class PrismSigningKey
{
public byte[] PublicKey = Array.Empty<byte>(); // 65 bytes, 0x04 | X | Y
public string PrivateJwk = ""; // JWK JSON, as on the site
}

/// <summary>Result of opening a secure envelope: payload, signature state and signer fingerprint.</summary>
public sealed class PrismSecureResult
{
public bool Secure, Encrypted, Signed;
Expand All @@ -37,6 +39,9 @@ public sealed class PrismSecureResult
public int Version;
}

/// <summary>Comb Code Secure (envelope v2, reads v1): AES-256-GCM payload locking with Argon2id
/// (128 MiB, 3 passes, RFC 9106) or PBKDF2-SHA256 (600,000 rounds), and ECDSA P-256 / SHA-256
/// signing with the site's key formats and XXXX-XXXX fingerprints.</summary>
public static class PrismSecure
{
private static readonly byte[] MAGIC = { 0x50, 0x53, 0x43 }; // "PSC"
Expand Down Expand Up @@ -78,6 +83,7 @@ private static byte[] DeriveKeyBytes(string password, byte[] salt, int kdf, int
finally { Array.Clear(pw); }
}

/// <summary>Generate a new ECDSA P-256 signing key.</summary>
public static PrismSigningKey GenerateSigningKey()
{
using var ec = ECDsa.Create(ECCurve.NamedCurves.nistP256);
Expand Down Expand Up @@ -118,6 +124,7 @@ byte[] Unb64(string s)
return ec;
}

/// <summary>XXXX-XXXX fingerprint of a raw 65-byte public key.</summary>
public static string Fingerprint(byte[] publicKey65)
{
byte[] h = SHA256.HashData(publicKey65);
Expand All @@ -131,6 +138,7 @@ public static string Fingerprint(byte[] publicKey65)
}

/// <summary>Seal payload bytes: lock with a password and/or sign. kdf: "argon2id" (default) or "pbkdf2".</summary>
/// <summary>Seal a payload into a secure envelope, optionally password-locked and/or signed.</summary>
public static byte[] Seal(byte[] payload, string? password = null, PrismSigningKey? signWith = null, string kdf = "argon2id")
{
if (password == null && signWith == null)
Expand Down Expand Up @@ -162,15 +170,18 @@ public static byte[] Seal(byte[] payload, string? password = null, PrismSigningK
}
}

/// <summary>True when the bytes are a Comb Code Secure envelope.</summary>
public static bool IsSecure(byte[] b) =>
b.Length >= 6 && b[0] == MAGIC[0] && b[1] == MAGIC[1] && b[2] == MAGIC[2] &&
(b[3] == 1 || b[3] == 2) && (b[4] & ~3) == 0;

/// <summary>Report whether the bytes are a secure envelope, locked and/or signed, without opening it.</summary>
public static (bool secure, bool encrypted, bool signed) Inspect(byte[] b) =>
!IsSecure(b) ? (false, false, false) : (true, (b[4] & F_ENC) != 0, (b[4] & F_SIG) != 0);

/// <summary>Random passphrase: 7 groups of 4 from a 32-symbol alphabet = 140 bits
/// of entropy (32 symbols = exactly 5 bits each, so no modulo bias).</summary>
/// <summary>Generate a memorable passphrase in the site's wordlist format.</summary>
public static string GeneratePassphrase()
{
const string ALPHA = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
Expand All @@ -191,6 +202,7 @@ public static string GeneratePassphrase()
private static readonly string[] COMMON_WORDS = { "password", "passw0rd", "qwerty", "letmein", "welcome", "admin", "iloveyou", "monkey", "dragon", "football", "baseball", "shalom", "israel", "master", "login", "abc123", "prism", "secret", "hello", "test", "summer", "winter", "sunshine", "princess", "trustno1", "whatever", "google", "avi", "1234", "asdf", "zxcv", "love", "god", "cohen", "levi" };

/// <summary>Strength estimate in bits, same heuristic as the site (deliberately cautious).</summary>
/// <summary>The site's password strength meter: entropy bits, 0..4 level, label and warnings.</summary>
public static (int bits, int level, string label, string[] warnings) Strength(string pw)
{
var warnings = new List<string>();
Expand Down Expand Up @@ -226,6 +238,8 @@ public static (int bits, int level, string label, string[] warnings) Strength(st
}

/// <summary>Open a sealed payload. Plain (non-secure) payloads come back unchanged.</summary>
/// <summary>Open a secure envelope. A locked envelope needs <paramref name="password"/>;
/// pass <paramref name="trustedFingerprints"/> to verify the signer.</summary>
public static PrismSecureResult Open(byte[] bytes, string? password = null, string[]? trustedFingerprints = null)
{
var outp = new PrismSecureResult();
Expand Down
8 changes: 4 additions & 4 deletions ports/csharp/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ static int Main(string[] args)
Console.WriteLine("size cells color-ecc0 bw-ecc0 (max payload bytes; ecc1/2/3 fit less)");
string[] cells = { "21x24", "29x33", "41x47", "57x66", "81x94", "113x130" };
for (int s = 0; s < 6; s++)
Console.WriteLine($"{s} {cells[s],-10} {Prism.CapacityPayload(s, 0, PrismMode.Color),-11} {Prism.CapacityPayload(s, 0, PrismMode.BW),-8}");
Console.WriteLine($"{s} {cells[s],-10} {Comb.CapacityPayload(s, 0, PrismMode.Color),-11} {Comb.CapacityPayload(s, 0, PrismMode.BW),-8}");
return 0;
}
if (args[0] == "encode")
Expand Down Expand Up @@ -97,7 +97,7 @@ string Next()
data = PrismSecure.Seal(data, password, keyFile != null ? LoadKey(keyFile) : null, kdf);
type = (int)PrismType.Binary;
}
Prism.EncodePng(data, outp, size, ecc, mode, (PrismType)type, scale);
Comb.EncodePng(data, outp, size, ecc, mode, (PrismType)type, scale);
Console.WriteLine($"wrote {outp} ({data.Length} payload bytes)");
return 0;
}
Expand Down Expand Up @@ -185,7 +185,7 @@ string Next()
else { Usage(); return 2; }
}
if (inp == null) { Usage(); return 2; }
var res = Prism.DecodePng(inp);
var res = Comb.DecodePng(inp);
if (PrismSecure.IsSecure(res.Bytes))
{
var opened = PrismSecure.Open(res.Bytes, password);
Expand Down Expand Up @@ -334,7 +334,7 @@ string Next()
}
if (inp == null) { Usage(); return 2; }
byte[] bytes = inp.EndsWith(".png", StringComparison.OrdinalIgnoreCase)
? Prism.DecodePng(inp).Bytes
? Comb.DecodePng(inp).Bytes
: File.ReadAllBytes(inp);
var id = PrismIssuers.Identify(bytes);
if (id == null) { Console.WriteLine("not a signed Comb Code Secure payload"); return 0; }
Expand Down
Loading