Hash Functions in Programming
Using hash functions in Python, JavaScript, and Go — SHA-256, MD5, and BLAKE2 with code examples.
Published:
Tags: hash functions programming, SHA-256 in Python JavaScript, hash code examples
Hash Functions in Programming The NIST FIPS 180-4 standard defines the SHA family of cryptographic hash functions. The NIST SP 800-107 provides recommendations for applications using approved hash algorithms. For password hashing, NIST SP 800-63B recommends Argon2 or bcrypt. Hash functions take an arbitrary input and return a fixed-length digest. This guide shows concrete implementations in Python, JavaScript, and Go — covering strings, files, and streaming input — along with notes on which function to use for each purpose. --- Python: hashlib Python's module is part of the standard library and covers the full SHA-2 family, SHA-3, BLAKE2, and legacy algorithms. String hashing File hashing Feed large files in chunks to avoid loading them entirely into memory: HMAC (keyed hashing)…
Frequently Asked Questions
How do I calculate SHA-256 in JavaScript?
Use the Web Crypto API: `const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(str))`, then convert the ArrayBuffer to a hex string using `Array.from(new Uint8Array(digest)).map(b => b.toString(16).padStart(2,'0')).join('')`.
How do I hash a file in Python?
Open the file in binary mode and feed it to hashlib in chunks: `import hashlib; h = hashlib.sha256(); open('file','rb') as f: [h.update(chunk) for chunk in iter(lambda: f.read(65536), b'')]; print(h.hexdigest())`.
How do I use SHA-256 in Go?
Import `crypto/sha256` and call `sha256.Sum256([]byte(input))`. For streaming large files use `h := sha256.New(); io.Copy(h, file); hex.EncodeToString(h.Sum(nil))`.
What is the hashlib module in Python?
hashlib is Python's standard library module for cryptographic hashing. It provides SHA-256, SHA-512, SHA-3, BLAKE2b, MD5, and more. Use `hashlib.sha256(data).hexdigest()` for a one-liner. For password hashing, use `hashlib.scrypt()` or the `bcrypt` package instead.
How do I hash binary data?
Hash functions accept raw bytes — pass the binary data directly without encoding it as a string. In Python pass the bytes object directly to hashlib. In JavaScript pass a Uint8Array or ArrayBuffer to crypto.subtle.digest(). In Go pass a []byte slice.
All articles · theproductguy.in