Re: Factor

Factor: the language, the theory, and the practice.

SHA-256 from URL

Tuesday, September 12, 2023

#checksums #networking

Álvaro Ramírez wrote a blog post about generating a SHA-256 hash from URL, the easy way where they describe wanting to download a file and generate a SHA-256 hash of the contents easily. Their solution involves copying a URL and then having some Emacs Lisp be able to read the clipboard, download the file, then generate and return the hash on the clipboard.

I thought I’d show how this can be done in Factor, by breaking the problem into smaller parts.

USING: checksums checksums.sha http.client io.directories io.files.temp kernel
math.parser namespaces sequences ui.clipboards ;

The first step is downloading a file to a temporary file, returning the path of the downloaded file:

: download-to-temp ( url -- path )
    dup download-name temp-file [
        [ ?delete-file ] [ download-to ] bi
    ] keep ;

The next step is to build a word that applies a checksum to the downloaded file contents:

: checksum-url ( url checksum -- value )
    [ download-to-temp ] [ checksum-file ] bi* ;

The last step is to use the clipboard to access the URL that was copied – checking minimally that it looks like an http or https URL – and then putting the checksum value back onto the clipboard:

: checksum-clipboard ( checksum -- )
    clipboard get clipboard-contents
    dup "http" head? [ throw ] unless
    swap checksum-url bytes>hex-string
    clipboard get set-clipboard-contents ;

This could be improved with better error checking, and maybe cleaning up the temporary file that was downloaded after running the checksum.

Give it a try!

IN: scratchpad sha-256 checksum-clipboard