Skip to content

crypto

Cryptographic hashing, HMAC, UUID generation, and random bytes. All hash outputs are lowercase hex strings.

Version v0.1
Platform PC, ESP32
Type Native (C)

star.mod

require dev-libs/crypto v0.1

Usage

import "crypto"

Functions

Hashing

Function Signature Description
crypto.sha256(data) (string) -> string SHA-256 hash, returns 64 hex chars
crypto.sha512(data) (string) -> string SHA-512 hash, returns 128 hex chars
var hash: string = crypto.sha256("hello")
# "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"

var h512: string = crypto.sha512("hello")
# 128-char hex string

HMAC

Function Signature Description
crypto.hmac256(key, data) (string, string) -> string HMAC-SHA256, returns 64 hex chars
crypto.hmac512(key, data) (string, string) -> string HMAC-SHA512, returns 128 hex chars
var mac: string = crypto.hmac256("secret-key", "message")
# use for API authentication, message signing, etc.

UUID

Function Signature Description
crypto.uuid() () -> string Generate UUID v4 (random), 36 chars
var id: string = crypto.uuid()
# "550e8400-e29b-41d4-a716-446655440000" (format: 8-4-4-4-12)

UUID v4 uses /dev/urandom for random bytes, sets version (4) and variant (1) bits per RFC 4122.

Random Bytes

Function Signature Description
crypto.randomBytes(n) (i32) -> string N random bytes as hex string (2N chars)
var token: string = crypto.randomBytes(32)
# 64 hex chars of cryptographic random data

var nonce: string = crypto.randomBytes(16)
# 32 hex chars

Maximum 1024 bytes per call. Values below 1 or above 1024 default to 16.

Base64

Function Signature Description
crypto.base64Encode(data) (string) -> string Encode string to Base64
crypto.base64Decode(data) (string) -> string Decode Base64 to string
var encoded: string = crypto.base64Encode("Hello World")
# "SGVsbG8gV29ybGQ="

var decoded: string = crypto.base64Decode(encoded)
# "Hello World"

Standard Base64 alphabet (RFC 4648) with = padding.

Pattern: API Request Signing

package main

import "crypto"
import "time"
import "json"

fn sign_request(api_key: string, body: string):string {
    var ts: string = time.format(time.now(), "%Y%m%d%H%M%S")
    var payload: string = ts + ":" + body
    var sig: string = crypto.hmac256(api_key, payload)
    return sig
}

fn main():void {
    var key: string = "my-secret-key"
    var body: string = "{\"sensor\":42}"
    var sig: string = sign_request(key, body)
    console.log(sig)
}

Notes

  • All hash functions are FIPS 180-4 compliant (SHA-256, SHA-512)
  • HMAC follows RFC 2104 / RFC 4231
  • UUID follows RFC 4122 v4
  • Random source: /dev/urandom on Linux/macOS, ESP32 uses hardware RNG
  • Zero external dependencies — standalone C implementation
  • Hash output is always lowercase hex
  • Base64 follows RFC 4648 standard alphabet