Wasm Builders 🧱

Connor Hicks for Suborbital

Posted on

A simple data hashing serverless function using Sat

Something I found myself needing recently was the ability to get a cryptographic hash for a piece of data, specifically the SHA256 value for a file. I wanted to encapsulate this into a very simple serverless function, so I built and deployed it with Sat, our tiny WebAssembly function server! It took only 3 quick steps, so I thought I'd share:

Create the function

Make sure you install Sat and Subo, the Suborbital CLI, if you haven't already

Creating the function (using Go, my most familiar language), is just one command:

subo create runnable sha256 --lang go
Enter fullscreen mode Exit fullscreen mode

This sets up a Go function that is designed to be compiled to Wasm using TinyGo, which Subo can do automatically for you.

The function implementation

For this function, I needed to take the data passed into the function, generate the SHA256 value, and return it as a Base64URL-encoded string. Luckily, the Go code required to do this is fairly simple:

package main

import (


type Sha256 struct{}

func (h Sha256) Run(input []byte) ([]byte, error) {
    hasher := sha256.New()

    hashBytes := hasher.Sum(nil)

    hashString := base64.URLEncoding.EncodeToString(hashBytes)

    return []byte(hashString), nil

// initialize runnable, do not edit //
func main() {
Enter fullscreen mode Exit fullscreen mode

As you can see, using the crypto package from the Go standard library, we can create a hasher, write the input data to it, encode the result, and return it as output. As simple as that!

Build and run the function

With Subo, the TinyGo toolchain is available as a Docker container, so if you have Docker running on your machine, all you need to do is run one command:

subo build sha256
ℹ️  building single Runnable (run from project root to create bundle)
⏩ START: building runnable: sha256 (tinygo)
✅ DONE: sha256 was built -> /Users/cohix-14/Workspaces/cohix/sat-demos/sha256/sha256.wasm
Enter fullscreen mode Exit fullscreen mode

And the function is compiled to Wasm! Running it with Sat is just as simple:

SAT_HTTP_PORT=9090 sat ./sha256/sha256.wasm
Enter fullscreen mode Exit fullscreen mode

To test it out, use something like cURL:

curl -d 'woah there' localhost:9090
Enter fullscreen mode Exit fullscreen mode

Heck yeah, as simple as can be! Sat can be configured to automatically acquire a TLS certificate using LetsEncrypt, so if you want to deploy this service on the public internet, you can add SAT_DOMAIN=example.com as well for automatic HTTPS!

That's all for now, happy building!

Top comments (1)

aryank21 profile image
Aryan Kaushik