三十的博客

Go 加密算法使用入门指南

本文内容基于 AI 生成结果整理,可能包含不准确信息,仅供参考使用。
发布时间
阅读量 加载中...

MD5 加密

Go 实现

go
package main

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

func main() {
	data := "hello world"

	// 创建MD5哈希对象
	hash := md5.New()

	// 写入要加密的数据
	hash.Write([]byte(data))

	// 计算哈希值并转换为16进制字符串
	md5Hash := hex.EncodeToString(hash.Sum(nil))

	fmt.Println("MD5:", md5Hash)
}

PHP 对比

php
<?php
$data = "hello world";
$md5Hash = md5($data);
echo "MD5: " . $md5Hash;
?>

解释

  1. md5.New()- 创建一个新的 MD5 哈希对象
  2. hash.Write([]byte(data))- 将字符串转换为字节切片并写入哈希对象
  3. hash.Sum(nil)- 计算哈希值,返回字节切片
  4. hex.EncodeToString()- 将字节切片转换为 16 进制字符串

在 PHP 中,md5()函数直接返回 16 进制字符串,而 Go 需要更多步骤,因为 Go 更强调显式操作。

SHA1 加密

Go 实现

go
package main

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

func main() {
	data := "hello world"

	// 创建SHA1哈希对象
	hash := sha1.New()

	// 写入要加密的数据
	hash.Write([]byte(data))

	// 计算哈希值并转换为16进制字符串
	sha1Hash := hex.EncodeToString(hash.Sum(nil))

	fmt.Println("SHA1:", sha1Hash)
}

PHP 对比

php
<?php
$data = "hello world";
$sha1Hash = sha1($data);
echo "SHA1: " . $sha1Hash;
?>

解释

SHA1 的实现与 MD5 几乎相同,只是使用了 crypto/sha1 包而不是 crypto/md5。

SHA256 加密

Go 实现

go
package main

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

func main() {
	data := "hello world"

	// 创建SHA256哈希对象
	hash := sha256.New()

	// 写入要加密的数据
	hash.Write([]byte(data))

	// 计算哈希值并转换为16进制字符串
	sha256Hash := hex.EncodeToString(hash.Sum(nil))

	fmt.Println("SHA256:", sha256Hash)
}

PHP 对比

php
<?php
$data = "hello world";
$sha256Hash = hash('sha256', $data);
echo "SHA256: " . $sha256Hash;
?>

解释

SHA256 的实现与前两者类似,使用 crypto/sha256 包。在 PHP 中需要使用 hash()函数并指定’sha256’算法。

简化版封装

如果你觉得每次都要写这么多代码太麻烦,可以像 PHP 那样封装一个简单的函数:

go
package main

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

func MD5(data string) string {
	hash := md5.New()
	hash.Write([]byte(data))
	return hex.EncodeToString(hash.Sum(nil))
}

func SHA1(data string) string {
	hash := sha1.New()
	hash.Write([]byte(data))
	return hex.EncodeToString(hash.Sum(nil))
}

func SHA256(data string) string {
	hash := sha256.New()
	hash.Write([]byte(data))
	return hex.EncodeToString(hash.Sum(nil))
}

func main() {
	data := "hello world"

	fmt.Println("MD5:", MD5(data))
	fmt.Println("SHA1:", SHA1(data))
	fmt.Println("SHA256:", SHA256(data))
}

安全性说明

  1. MD5​ 和 ​SHA1​ 已经被认为是不安全的加密算法,不建议用于密码存储等安全敏感场景
  2. SHA256​ 是目前较为安全的哈希算法,常用于密码存储(但通常还需要加盐)
  3. 对于密码存储,建议使用专门的密码哈希算法如 bcrypt、scrypt 或 Argon2

加盐哈希示例

安全做法是给哈希加盐(salt):

go
package main

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

func HashWithSalt(data, salt string) string {
	hash := sha256.New()
	hash.Write([]byte(data + salt))
	return hex.EncodeToString(hash.Sum(nil))
}

func main() {
	data := "mypassword"
	salt := "randomsalt123"

	hashed := HashWithSalt(data, salt)
	fmt.Println("Salted SHA256:", hashed)
}
#加密算法 #Golang