Hash Generator — Ruby source
Compute SHA-1, SHA-256, SHA-384 and SHA-512 hashes of any text at once, using the browser's native SubtleCrypto. Copy each digest. 100% client-side.
This is the Ruby implementation — the same logic the interactive tool runs, in a shareable, citable form.
# hash — SHA-1 / SHA-256 / SHA-384 / SHA-512 digest of a UTF-8 string.
#
# Language: Ruby 3.2 (standard library: digest)
# Source: CosmoDev polyglot showcase port of the `hash` tool, ported from
# src/tools/HashGenerator.tsx (the canonical TypeScript island).
# License: display source — part of CosmoDev's polyglot tool pages.
#
# Unkeyed SHA digests via Ruby's bundled `digest` library — C extensions
# shipped with the Ruby distribution (digest/sha1 and digest/sha2), so no
# gems are required. Digest::SHA384 lives in digest/sha2 alongside SHA-256
# and SHA-512. `hexdigest` returns exactly the lowercase hex the TypeScript
# reference produces.
#
# Behavior mirrors the TypeScript reference: UTF-8 input, lowercase hex
# output, and rejection of unknown algorithm names. A Ruby String is a byte
# sequence with an encoding, so a UTF-8 string hashes as its own bytes — the
# same byte sequence a browser hands to crypto.subtle.digest. SHA-1 is
# offered for legacy compatibility only; it is not collision-resistant.
require 'digest/sha1'
require 'digest/sha2'
module HashTool
# Canonical algorithm names. The spellings match the TypeScript union so
# the same string works across every port.
SHA1 = 'SHA-1'
SHA256 = 'SHA-256' # default algorithm
SHA384 = 'SHA-384'
SHA512 = 'SHA-512'
# Dispatch table: canonical name -> Digest class. Module-level so the
# supported set is visible in one place and easy to extend (the same shape
# as the Python port's _HASH_CONSTRUCTORS).
ALGORITHMS = {
SHA1 => Digest::SHA1,
SHA256 => Digest::SHA256,
SHA384 => Digest::SHA384,
SHA512 => Digest::SHA512
}.freeze
module_function
# Computes the named digest of `text` and returns it as lowercase hex.
#
# A nil or empty `algorithm` selects SHA-256 — the optional-parameter
# default the TypeScript reference declares. An unknown name raises
# ArgumentError (not KeyError), matching the Python port's ValueError.
def digest(text, algorithm = SHA256)
name = algorithm.to_s.empty? ? SHA256 : algorithm
klass = ALGORITHMS.fetch(name) do
raise ArgumentError, "Unsupported hash algorithm: #{name}"
end
klass.hexdigest(text)
end
# Computes every supported digest of `text` — the Ruby shape of the Record
# the React island renders. Each hash is independent, and the hash keeps
# the canonical algorithm order (Ruby hashes preserve insertion order).
def hash_all(text)
ALGORITHMS.keys.to_h { |alg| [alg, digest(text, alg)] }
end
end
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →