Md5 Checksums For Legacy Compatibility

Compute MD5 digests with crypto/md5 in one-shot and streaming forms, and keep the warning: known collisions make it unfit for any security purpose.

GoData Integrity

Code

gosnippet
24 lines
package main

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
)

func main() {
	for _, payload := range []string{"hello", "hello!", "hello world"} {
		sum := md5.Sum([]byte(payload))
		fmt.Printf("md5(%q) = %s
", payload, hex.EncodeToString(sum[:]))
	}

	// 流式写法:分片写进 hash.Hash 再取 Sum,适合大文件
	digest := md5.New()
	digest.Write([]byte("chunk-1|"))
	digest.Write([]byte("chunk-2"))
	fmt.Println("streamed:", hex.EncodeToString(digest.Sum(nil)))

	// MD5 不再具有密码学安全性:只用于兼容既有校验和与缓存键
	fmt.Println("collisions known since 2004, use SHA-256 for new designs")
}

The story the code tells

Structurally, expect the function main and nothing else.

for _, payload := range []string{"hello", "hello!", "hello world"} is the loop that carries the per-item work.

Caveats

  • All standard library — paste it in and it works as-is.

Putting it to use

Entry signature: func main()

The run prints streamed: — each prefix names the step that produced it.

Core lines

for _, payload := range []string{"hello", "hello!", "hello world"} {
	sum := md5.Sum([]byte(payload))
	fmt.Printf("md5(%q) = %s
", payload, hex.EncodeToString(sum[:]))
}

Interactive Tools for This Topic

FAQ

What does Md5 Checksums For Legacy Compatibility print when run?
Run it as a complete program — the output lines carry labels such as `streamed:`.