Browser Fingerprint Viewer — Rust source
See exactly what websites can learn about your browser without cookies — screen, GPU, fonts, timezone, language, and more. Educational, not tracking.
This is the Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.
// browser-fingerprint — Rust polyglot showcase port (pure analysis layer).
//
// Ported from the TypeScript reference at src/lib/browser-fingerprint.ts.
// Covers the portable core: the 18-signal registry with privacy-risk
// classifications, canonical category grouping, risk counts, and the stable
// SHA-256 fingerprint hash. The browser-API collection layer (canvas / WebGL
// / font probes) is DOM-bound by design and does not port.
//
// SHA-256 note: the Rust standard library deliberately ships no
// cryptographic primitives. In production, hash with the audited `sha2`
// crate (sha2 = "0.10"); this snippet hand-rolls FIPS 180-4 SHA-256 only to
// stay dependency-free and self-contained. The "abc" test vector below pins
// the implementation to the specification.
//
// Display source — part of CosmoDev's polyglot tool pages.
use std::fmt::Write as _;
/// Privacy-risk classification.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum RiskLevel {
/// Near-unique on its own or part of a rare combination.
High,
/// Narrows you to a sizable-but-specific population.
Medium,
/// Coarse; shared by millions of browsers.
Low,
}
impl RiskLevel {
pub fn as_str(self) -> &'static str {
match self {
RiskLevel::Low => "low",
RiskLevel::Medium => "medium",
RiskLevel::High => "high",
}
}
}
/// Groups related signals.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum FingerprintCategory {
Hardware,
Graphics,
Network,
Browser,
Input,
}
impl FingerprintCategory {
pub fn as_str(self) -> &'static str {
match self {
FingerprintCategory::Hardware => "Hardware",
FingerprintCategory::Graphics => "Graphics",
FingerprintCategory::Network => "Network",
FingerprintCategory::Browser => "Browser",
FingerprintCategory::Input => "Input",
}
}
}
/// Canonical category order (card grid, top to bottom).
pub const FINGERPRINT_CATEGORIES: [FingerprintCategory; 5] = [
FingerprintCategory::Hardware,
FingerprintCategory::Graphics,
FingerprintCategory::Network,
FingerprintCategory::Browser,
FingerprintCategory::Input,
];
/// One collected, classified signal.
#[derive(Clone, Debug)]
pub struct FingerprintSignal {
pub id: &'static str,
pub label: &'static str,
pub value: String,
pub risk: RiskLevel,
pub category: FingerprintCategory,
}
/// Classifies one signal id.
struct SignalDef {
label: &'static str,
risk: RiskLevel,
category: FingerprintCategory,
}
/// Static registry of every signal the tool collects, with its privacy-risk
/// classification. Single source of truth: build_signal() derives from it,
/// so a signal can never be collected without being classified. A const
/// array keeps the registry readable; signal_def() scans it (18 entries).
const SIGNAL_DEFINITIONS: [(&str, SignalDef); 18] = [
// High risk
("canvas", SignalDef { label: "Canvas fingerprint", risk: RiskLevel::High, category: FingerprintCategory::Graphics }),
("webgl-renderer", SignalDef { label: "WebGL renderer", risk: RiskLevel::High, category: FingerprintCategory::Graphics }),
("webgl-vendor", SignalDef { label: "WebGL vendor", risk: RiskLevel::High, category: FingerprintCategory::Graphics }),
("fonts", SignalDef { label: "Installed fonts", risk: RiskLevel::High, category: FingerprintCategory::Browser }),
("timezone", SignalDef { label: "Timezone", risk: RiskLevel::High, category: FingerprintCategory::Browser }),
// Medium risk
("screen", SignalDef { label: "Screen & color depth", risk: RiskLevel::Medium, category: FingerprintCategory::Hardware }),
("device-pixel-ratio", SignalDef { label: "Device pixel ratio", risk: RiskLevel::Medium, category: FingerprintCategory::Hardware }),
("hardware-concurrency", SignalDef { label: "CPU cores", risk: RiskLevel::Medium, category: FingerprintCategory::Hardware }),
("device-memory", SignalDef { label: "Device Memory", risk: RiskLevel::Medium, category: FingerprintCategory::Hardware }),
("platform", SignalDef { label: "Platform", risk: RiskLevel::Medium, category: FingerprintCategory::Browser }),
("languages", SignalDef { label: "Languages", risk: RiskLevel::Medium, category: FingerprintCategory::Browser }),
("touch", SignalDef { label: "Touch support", risk: RiskLevel::Medium, category: FingerprintCategory::Input }),
("connection", SignalDef { label: "Connection type", risk: RiskLevel::Medium, category: FingerprintCategory::Network }),
// Low risk
("user-agent", SignalDef { label: "User agent", risk: RiskLevel::Low, category: FingerprintCategory::Browser }),
("do-not-track", SignalDef { label: "Do Not Track", risk: RiskLevel::Low, category: FingerprintCategory::Browser }),
("cookies-enabled", SignalDef { label: "Cookies enabled", risk: RiskLevel::Low, category: FingerprintCategory::Browser }),
("online", SignalDef { label: "Online status", risk: RiskLevel::Low, category: FingerprintCategory::Network }),
("pdf-viewer", SignalDef { label: "PDF viewer", risk: RiskLevel::Low, category: FingerprintCategory::Browser }),
];
fn signal_def(id: &str) -> Option<&'static SignalDef> {
SIGNAL_DEFINITIONS
.iter()
.find(|(key, _)| *key == id)
.map(|(_, def)| def)
}
/// Risk level for a known signal id; None for unknown ids.
pub fn classify_signal_risk(id: &str) -> Option<RiskLevel> {
signal_def(id).map(|def| def.risk)
}
/// Build a signal from its id and collected value. Errors on unknown ids so
/// a typo'd id fails loudly instead of silently rendering an unclassified
/// row.
pub fn build_signal(id: &'static str, value: impl Into<String>) -> Result<FingerprintSignal, String> {
let def = signal_def(id).ok_or_else(|| format!("Unknown fingerprint signal id: {id}"))?;
Ok(FingerprintSignal {
id,
label: def.label,
value: value.into(),
risk: def.risk,
category: def.category,
})
}
/// One category and its signals.
pub struct CategoryGroup {
pub category: FingerprintCategory,
pub signals: Vec<FingerprintSignal>,
}
/// Group signals by category in canonical order, omitting empty categories.
pub fn group_by_category(signals: &[FingerprintSignal]) -> Vec<CategoryGroup> {
let mut groups = Vec::new();
for &category in FINGERPRINT_CATEGORIES.iter() {
let members: Vec<FingerprintSignal> = signals
.iter()
.filter(|signal| signal.category == category)
.cloned()
.collect();
if !members.is_empty() {
groups.push(CategoryGroup { category, signals: members });
}
}
groups
}
/// Signals per risk level (drives the summary line).
pub struct RiskCounts {
pub low: usize,
pub medium: usize,
pub high: usize,
}
/// Count signals per risk level.
pub fn count_by_risk(signals: &[FingerprintSignal]) -> RiskCounts {
let mut counts = RiskCounts { low: 0, medium: 0, high: 0 };
for signal in signals {
match signal.risk {
RiskLevel::Low => counts.low += 1,
RiskLevel::Medium => counts.medium += 1,
RiskLevel::High => counts.high += 1,
}
}
counts
}
/// The exact byte string the fingerprint hash is computed over: every value
/// joined with | in signal order.
pub fn concat_signal_values(signals: &[FingerprintSignal]) -> String {
signals
.iter()
.map(|signal| signal.value.as_str())
.collect::<Vec<_>>()
.join("|")
}
// ---------------------------------------------------------------------------
// SHA-256 (FIPS 180-4) — dependency-free, pinned to the spec by tests
// ---------------------------------------------------------------------------
/// Round constants: first 32 bits of the fractional parts of the cube roots
/// of the first 64 primes.
const K: [u32; 64] = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
];
/// Initial hash words: first 32 bits of the fractional parts of the square
/// roots of the first 8 primes.
const H0: [u32; 8] = [
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
];
/// Minimal SHA-256 state machine (single-shot digest over a full message).
struct Sha256 {
state: [u32; 8],
}
impl Sha256 {
fn new() -> Self {
Sha256 { state: H0 }
}
/// Process one 64-byte block through the 64-round compression function.
fn compress(&mut self, block: &[u8; 64]) {
let mut w = [0u32; 64];
for (t, chunk) in block.chunks_exact(4).enumerate() {
w[t] = u32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
}
for t in 16..64 {
let s0 = w[t - 15].rotate_right(7) ^ w[t - 15].rotate_right(18) ^ (w[t - 15] >> 3);
let s1 = w[t - 2].rotate_right(17) ^ w[t - 2].rotate_right(19) ^ (w[t - 2] >> 10);
w[t] = w[t - 16]
.wrapping_add(s0)
.wrapping_add(w[t - 7])
.wrapping_add(s1);
}
let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = self.state;
for t in 0..64 {
let big_s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
let ch = (e & f) ^ (!e & g);
let temp1 = h
.wrapping_add(big_s1)
.wrapping_add(ch)
.wrapping_add(K[t])
.wrapping_add(w[t]);
let big_s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
let maj = (a & b) ^ (a & c) ^ (b & c);
let temp2 = big_s0.wrapping_add(maj);
h = g;
g = f;
f = e;
e = d.wrapping_add(temp1);
d = c;
c = b;
b = a;
a = temp1.wrapping_add(temp2);
}
for (word, delta) in self.state.iter_mut().zip([a, b, c, d, e, f, g, h]) {
*word = word.wrapping_add(delta);
}
}
/// Pad (0x80, zeros, 64-bit big-endian bit length) and digest the whole
/// message, returning the 32-byte hash.
fn digest(mut self, message: &[u8]) -> [u8; 32] {
let bit_len = (message.len() as u64).wrapping_mul(8);
let mut padded = message.to_vec();
padded.push(0x80);
while padded.len() % 64 != 56 {
padded.push(0);
}
padded.extend_from_slice(&bit_len.to_be_bytes());
for chunk in padded.chunks_exact(64) {
let mut block = [0u8; 64];
block.copy_from_slice(chunk);
self.compress(&block);
}
let mut out = [0u8; 32];
for (i, word) in self.state.iter().enumerate() {
out[4 * i..4 * i + 4].copy_from_slice(&word.to_be_bytes());
}
out
}
}
/// SHA-256 hex digest of the UTF-8 bytes of input.
pub fn sha256_hex(input: &str) -> String {
let digest = Sha256::new().digest(input.as_bytes());
let mut hex = String::with_capacity(64);
for byte in digest {
let _ = write!(hex, "{byte:02x}");
}
hex
}
/// Stable fingerprint ID: SHA-256 over every signal value, joined in signal
/// order. Same browser state -> same hash; any single changed value -> new
/// hash.
pub fn hash_fingerprint(signals: &[FingerprintSignal]) -> String {
sha256_hex(&concat_signal_values(signals))
}
#[cfg(test)]
mod tests {
use super::*;
/// FIPS 180-4 vector: SHA-256("abc").
const ABC_DIGEST: &str =
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
#[test]
fn sha256_matches_spec_vector() {
assert_eq!(sha256_hex("abc"), ABC_DIGEST);
// Empty-message vector.
assert_eq!(
sha256_hex(""),
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
);
// Two-block message (length > 55 bytes forces a second block).
assert_eq!(
sha256_hex("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"),
"248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"
);
}
#[test]
fn unknown_signal_id_is_rejected() {
assert!(build_signal("no-such-signal", "x").is_err());
assert_eq!(classify_signal_risk("canvas"), Some(RiskLevel::High));
assert_eq!(classify_signal_risk("no-such-signal"), None);
}
#[test]
fn hash_is_stable_and_value_sensitive() {
let signals = vec![
build_signal("timezone", "Europe/Paris").unwrap(),
build_signal("screen", "2560×1440 @ 24-bit").unwrap(),
];
let hash = hash_fingerprint(&signals);
assert_eq!(hash, hash_fingerprint(&signals));
let mut changed = signals.clone();
changed[1].value = "1920×1080 @ 24-bit".to_string();
assert_ne!(hash, hash_fingerprint(&changed));
}
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →