Playground
crc32.gno
// Package crc32 implements the CRC-32 checksum as a pure, reusable package.
//
// CRC-32 treats a message as one enormous binary number and takes the remainder
// of dividing it by a fixed polynomial. The bit-reflected, table-driven form
// implemented here is the one everything actually uses — zip, gzip, PNG, and
// Ethernet all speak IEEE.
//
// Three polynomials are provided:
//
// - IEEE (0xEDB88320) — zip/gzip/PNG. The default.
// - Castagnoli (0x82F63B78) — iSCSI/btrfs; better error detection.
// - Koopman (0xEB31D82E)
//
// A CRC is an ACCIDENT detector, not a security primitive: it is linear, so
// anyone can craft a different message with the same checksum. Never use it to
// authenticate anything.
//
// A live demo of this package is at
// [r/moul/x/daily/crc32demo](/r/nym-moultest123/x/daily/crc32demo/v0).
package crc32
import "strings"
// Common reversed polynomials.
const (
IEEE = 0xEDB88320
Castagnoli = 0x82F63B78
Koopman = 0xEB31D82E
)
// Table is a precomputed byte-wise lookup table for one polynomial.
type Table [256]uint32
// MakeTable builds the lookup table for a reversed polynomial. Building it once
// and reusing it is the whole point of the table-driven form: it trades 1 KiB
// for eight bit-shifts per byte.
func MakeTable(poly uint32) *Table {
var t Table
for i := 0; i < 256; i++ {
crc := uint32(i)
for j := 0; j < 8; j++ {
if crc&1 != 0 {
crc = (crc >> 1) ^ poly
} else {
crc >>= 1
}
}
t[i] = crc
}
return &t
}
var ieeeTable = MakeTable(IEEE)
// Update adds the bytes of s to a running checksum.
//
// Takes and returns the RAW register, not the final value: the caller-visible
// checksum is the register XOR 0xFFFFFFFF, so chaining Update calls on final
// values would be wrong. Start from 0 and finish with Finalize.
func Update(crc uint32, t *Table, s string) uint32 {
for i := 0; i < len(s); i++ {
crc = t[byte(crc)^s[i]] ^ (crc >> 8)
}
return crc
}
// Finalize turns a running register into the checksum.
func Finalize(crc uint32) uint32 { return crc ^ 0xFFFFFFFF }
// ChecksumWith returns the CRC-32 of s under the given table.
func ChecksumWith(s string, t *Table) uint32 {
return Finalize(Update(0xFFFFFFFF, t, s))
}
// Checksum returns the IEEE CRC-32 of s — the one zip, gzip and PNG use.
func Checksum(s string) uint32 { return ChecksumWith(s, ieeeTable) }
// Hex renders a checksum as eight lowercase hex digits, zero-padded, which is
// how CRCs are conventionally shown.
func Hex(crc uint32) string {
const digits = "0123456789abcdef"
var b [8]byte
for i := 7; i >= 0; i-- {
b[i] = digits[crc&0xF]
crc >>= 4
}
return string(b[:])
}
// ChecksumHex is Checksum rendered with Hex.
func ChecksumHex(s string) string { return Hex(Checksum(s)) }
// Verify reports whether s has the expected checksum.
func Verify(s string, expected uint32) bool { return Checksum(s) == expected }
// Split returns the checksum of each line of s, in order.
func Split(s string) []string {
out := []string{}
for _, line := range strings.Split(s, "\n") {
out = append(out, ChecksumHex(line))
}
return out
}
crc32_test.gno
package crc32
import (
"strings"
"testing"
"gno.land/p/nt/uassert/v0"
)
// Known-answer tests against the published IEEE vectors.
func TestChecksumKnownVectors(t *testing.T) {
cases := []struct {
in string
want string
}{
{"", "00000000"},
{"a", "e8b7be43"},
{"abc", "352441c2"},
{"message digest", "20159d7f"},
{"abcdefghijklmnopqrstuvwxyz", "4c2750bd"},
{"123456789", "cbf43926"}, // the standard CRC check value
}
for _, c := range cases {
uassert.Equal(t, c.want, ChecksumHex(c.in))
}
}
// The classic "check" value: CRC-32/IEEE of "123456789" is 0xCBF43926.
func TestStandardCheckValue(t *testing.T) {
uassert.Equal(t, uint32(0xCBF43926), Checksum("123456789"))
}
func TestHexIsZeroPadded(t *testing.T) {
uassert.Equal(t, "00000000", Hex(0))
uassert.Equal(t, "0000000f", Hex(15))
uassert.Equal(t, "ffffffff", Hex(0xFFFFFFFF))
uassert.Equal(t, 8, len(Hex(1)))
}
// A single flipped bit must change the checksum — the entire point.
func TestDetectsSingleBitChange(t *testing.T) {
base := Checksum("hello world")
uassert.False(t, base == Checksum("hello worle"))
uassert.False(t, base == Checksum("Hello world"))
}
// Order matters: a CRC is not a sum.
func TestOrderSensitive(t *testing.T) {
uassert.False(t, Checksum("ab") == Checksum("ba"))
}
func TestVerify(t *testing.T) {
uassert.True(t, Verify("abc", 0x352441C2))
uassert.False(t, Verify("abd", 0x352441C2))
}
// Chaining Update over chunks must equal one shot over the whole message —
// this is why Update takes the raw register rather than a final value.
func TestUpdateIsChunkable(t *testing.T) {
whole := Checksum("hello world")
crc := uint32(0xFFFFFFFF)
crc = Update(crc, ieeeTable, "hello ")
crc = Update(crc, ieeeTable, "world")
uassert.Equal(t, whole, Finalize(crc))
}
// Different polynomials must give different answers, and each be stable.
func TestAlternatePolynomials(t *testing.T) {
c := MakeTable(Castagnoli)
k := MakeTable(Koopman)
a := ChecksumWith("123456789", c)
b := ChecksumWith("123456789", k)
uassert.False(t, a == Checksum("123456789"))
uassert.False(t, a == b)
uassert.Equal(t, a, ChecksumWith("123456789", c)) // stable
}
func TestSplit(t *testing.T) {
got := Split("a\nabc")
uassert.Equal(t, 2, len(got))
uassert.Equal(t, "e8b7be43", got[0])
uassert.Equal(t, "352441c2", got[1])
}
func TestLongInput(t *testing.T) {
s := strings.Repeat("gno", 1000)
uassert.Equal(t, 8, len(ChecksumHex(s)))
uassert.Equal(t, Checksum(s), Checksum(s))
}
gnomod.toml
module = "gno.land/p/nym-moultest123/x/daily/crc32/v0" gno = "0.9" [addpkg] creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv" height = 186405 max_deposit = "5000000ugnot"