Go语言密码学:面向初学者的加密与哈希

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

Go语言(Golang)密码学:加密与哈希

Go(Golang)是一种现代编译型语言,以其高性能和对密码学算法的内置支持而闻名。标准库crypto提供了保护数据所需的一切:从简单的哈希到复杂的非对称加密。在本文中,我们将介绍主要工具并展示实际代码示例。



为什么Go语言需要密码学?

Go语言中的密码学用于:

  • 密码存储(哈希);
  • 网络数据传输(TLS/SSL);
  • 数字签名和身份验证;
  • 机密文件加密。

Go通过精心设计的API保证了安全性——很难意外使用过时或不安全的算法。



Go语言中的哈希

哈希是将数据单向转换为固定长度字符串的过程。在Go中,这由crypto/md5、crypto/sha1、crypto/sha256和crypto/sha512包负责。



示例:SHA-256哈希

package main

import ( "crypto/sha256" "fmt")

func main() { data := []byte("机密数据") hash := sha256.Sum256(data) fmt.Printf("SHA256: %x", hash)}

输出:SHA256: 3c3b...(64个字符)



带盐的密码哈希

为了安全存储密码,使用crypto/rand生成盐,并结合crypto/sha256:

package main

import ( "crypto/rand" "crypto/sha256" "fmt")

func main() { password := []byte("我的密码123") salt := make([]byte, 16) rand.Read(salt) salted := append(salt, password...) hash := sha256.Sum256(salted) fmt.Printf("盐: %x", salt) fmt.Printf("哈希: %x", hash)}

在实践中,密码最好使用bcrypt(golang.org/x/crypto/bcrypt包),但带盐的SHA-256是学习的不错选择。



对称加密:AES

AES(高级加密标准)是最流行的对称算法。在Go中,它通过crypto/aes包结合加密模式(crypto/cipher)实现。



示例:AES-GCM加密

package main

import ( "crypto/aes" "crypto/cipher" "crypto/rand" "fmt")

func main() { key := []byte("0123456789abcdef0123456789abcdef") // AES-256需要32字节 plaintext := []byte("机密消息") block, _ := aes.NewCipher(key) aead, _ := cipher.NewGCM(block) nonce := make([]byte, aead.NonceSize()) rand.Read(nonce) ciphertext := aead.Seal(nil, nonce, plaintext, nil) fmt.Printf("加密后: %x", ciphertext) // 解密 decrypted, _ := aead.Open(nil, nonce, ciphertext, nil) fmt.Printf("解密后: %s", decrypted)}

GCM(伽罗瓦/计数器模式)提供机密性和认证——是大多数任务的最佳选择。



非对称加密:RSA

RSA使用一对密钥(公钥和私钥)。在Go中,它通过crypto/rsa和crypto/rand实现。



密钥生成与加密

package main

import ( "crypto/rand" "crypto/rsa" "crypto/sha256" "fmt")

func main() { privateKey, _ := rsa.GenerateKey(rand.Reader, 2048) publicKey := &privateKey.PublicKey message := []byte("RSA的秘密") label := []byte("") // 使用公钥加密 ciphertext, _ := rsa.EncryptOAEP(sha256.New(), rand.Reader, publicKey, message, label) fmt.Printf("RSA加密后: %x", ciphertext) // 使用私钥解密 plaintext, _ := rsa.DecryptOAEP(sha

推荐