Python MD5 Hash Code Example (Online Runner)
Python MD5 hashing code example with runnable snippets to calculate MD5 and verify results online.
Online calculator: use the site MD5 text tool.
Calculation method
Use the standard library hashlib: encode text to bytes, then call md5().hexdigest() for a 32-character hex digest.
Implementation notes
- Package: built-in
hashlib(no external dependency). - Implementation: MD5 operates on bytes; the same text encoded differently will hash to different digests.
- Notes: MD5 is broken for collision resistance. Use it only for legacy checksums or non-security fingerprints.
python
import hashlib
def md5_text(text: str, encoding: str = "utf-8") -> str:
return hashlib.md5(text.encode(encoding)).hexdigest()
# Example usage
from hashlib import md5
payload = "hello world"
digest = md5(payload.encode("utf-8")).hexdigest()
print(digest)
File hashing example
python
from pathlib import Path
import hashlib
import tempfile
def md5_file(path: Path, chunk_size: int = 1024 * 1024) -> str:
hasher = hashlib.md5()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(chunk_size), b""):
hasher.update(chunk)
return hasher.hexdigest()
if __name__ == "__main__":
with tempfile.TemporaryDirectory() as temp_dir:
sample_path = Path(temp_dir) / "example.bin"
sample_path.write_bytes(b"example payload\n")
print(md5_file(sample_path))If you create files with echo, note it appends a newline by default. Use echo -n or include a \n byte to match
the same digest.
MD5 file hashes are computed from the file bytes only. The filename or path is not included unless you explicitly hash it as part of the input.
When to use MD5
MD5 is fast and widely supported, but it is not safe for security-sensitive hashing. Use it for checksums, fingerprinting, or legacy interoperability only. For security use cases, prefer SHA-256 or SHA-3.
Test vectors
| Input | Expected MD5 |
|---|---|
| (empty string) | d41d8cd98f00b204e9800998ecf8427e |
abc | 900150983cd24fb0d6963f7d28e17f72 |
message digest | f96b697d7cb7938d525a2f31aaf161d0 |
abcdefghijklmnopqrstuvwxyz | c3fcd3d76192e4007dfb496cca67e13b |
Complete script (implementation + tests)
python
import hashlib
TEST_VECTORS = {
"": "d41d8cd98f00b204e9800998ecf8427e",
"abc": "900150983cd24fb0d6963f7d28e17f72",
"message digest": "f96b697d7cb7938d525a2f31aaf161d0",
"abcdefghijklmnopqrstuvwxyz": "c3fcd3d76192e4007dfb496cca67e13b",
}
def md5_hex(data: bytes) -> str:
return hashlib.md5(data).hexdigest()
def md5_text(text: str, encoding: str = "utf-8") -> str:
return md5_hex(text.encode(encoding))
def run_tests() -> None:
for text, expected in TEST_VECTORS.items():
actual = md5_text(text)
assert actual == expected, f"MD5 mismatch for {text!r}: {actual} != {expected}"
print("All MD5 test vectors passed.")
if __name__ == "__main__":
run_tests()