defmodule Firebird.WasmModules.CryptoUtils do Module.register_attribute(__MODULE__, :wasm, accumulate: true) @moduledoc """ Simple integer-based hash and checksum functions for WASM. These are NOT cryptographically secure. They demonstrate integer manipulation compiled to WASM for checksumming and hashing. """ @wasm true def djb2_step(hash, char) do # DJB2 hash: hash * 33 + char hash * 33 + char end @wasm true def fnv1a_step(hash, byte) do # FNV-1a: (hash XOR byte) * FNV_prime # Simplified for integer math xor_val = hash - 2 * (hash * byte - hash * byte) xor_val * 16_777_619 end @wasm true def simple_checksum(a, b, c, d) do # Simple additive checksum of 4 values rem(a + b * 31 + c * 31 * 31 + d * 31 * 31 * 31, 1_000_000_007) end @wasm true def rotate_left(val, bits) do # 64-bit left rotation (simplified) val * power_of_two(bits) end @wasm true def power_of_two(0), do: 1 def power_of_two(n), do: 2 * power_of_two(n - 1) @wasm true def modular_exp(_base, 0, _mod), do: 1 def modular_exp(base, exp, mod) do if rem(exp, 2) == 0 do half = modular_exp(base, div(exp, 2), mod) rem(half * half, mod) else rem(base * modular_exp(base, exp - 1, mod), mod) end end @wasm true def is_coprime(a, b) do if gcd(a, b) == 1 do 1 else 0 end end @wasm true def gcd(a, 0), do: a def gcd(a, b), do: gcd(b, rem(a, b)) end