如何在Golang中使用crypto加密数据_Golang crypto加密操作方法汇总

Go语言中crypto包支持AES对称加密、RSA非对称加密、SHA256哈希及HMAC认证,适用于数据保护与完整性校验,需注意密钥长度、填充模式和安全随机数使用。

在Go语言中,crypto 包提供了多种加密算法和安全相关的功能,常用于数据加密、哈希计算、数字签名等场景。合理使用这些工具可以有效保护敏感数据的安全性。以下是常见的加密操作方法汇总,涵盖对称加密、非对称加密、哈希和HMAC的使用方式。

对称加密:使用AES进行数据加解密

AES(高级加密标准)是最常用的对称加密算法之一,Go通过 crypto/aescrypto/cipher 包支持。

说明: 对称加密使用相同的密钥进行加密和解密,适合加密大量数据。

示例代码(CBC模式):

package main

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

func encrypt(plaintext []byte, key []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { return nil, err }

ciphertext := make([]byte, aes.BlockSize+len(plaintext))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
    return nil, err
}

stream := cipher.NewCBCEncrypter(block, iv)
stream.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)

// 填充PKCS7
padding := aes.BlockSize - len(plaintext)%aes.BlockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
ciphertext = append(ciphertext, padtext...)

return ciphertext, nil

}

func decrypt(ciphertext []byte, key []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { return nil, err }

if len(ciphertext) < aes.BlockSize {
    return nil, errors.New("密文太短")
}

iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]

stream := cipher.NewCBCDecrypter(block, iv)
stream.CryptBlocks(ciphertext, ciphertext)

// 移除PKCS7填充
length := len(ciphertext)
unpadding := int(ciphertext[length-1])
if unpadding > length {
    return nil, errors.New("无效填充")
}
ciphertext = ciphertext[:length-unpadding]

return ciphertext, nil

}

注意: 密钥长度必须是16、24或32字节(对应AES-128、AES-192、AES-256)。

非对称加密:使用RSA加密和解密

RSA是一种广泛使用的非对称加密算法,公钥加密,私钥解密。

说明: 适合加密小量数据(如会话密钥),不适合直接加密大文本。

生成密钥对并加解密:

package main

import ( "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/pem" )

// 生成RSA密钥对 func generateRSAKey(bits int) (*rsa.PrivateKey, error) { return rsa.GenerateKey(rand.Reader, bits) }

// RSA加密 func rsaEncrypt(plaintext []byte, pubKey *rsa.PublicKey) ([]byte, error) { return rsa.EncryptPKCS1v15(rand.Reader, pubKey, plaintext) }

// RSA解密 func rsaDecrypt(ciphertext []byte, privKey *rsa.PrivateKey) ([]byte, error) { return rsa.DecryptPKCS1v15(rand.Reader, privKey, ciphertext) }

// 保存私钥为PEM格式 func savePrivateKey(key *rsa.PrivateKey) []byte { keyBytes := x509.MarshalPKCS1PrivateKey(key) pemBlock := &pem.Block{ Type: "RSA PRIVATE KEY", Bytes: keyBytes, } return pem.EncodeToMemory(pemBlock) }

// 加载私钥 func loadPrivateKey(pemData []byte) (*rsa.PrivateKey, error) { block, _ := pem.Decode(pemData) return x509.ParsePKCS1PrivateKey(block.Bytes) }

哈希计算:使用SHA256生成摘要

哈希函数用于生成数据的“指纹”,不可逆,常用于校验完整性或密码存储。

常见算法: SHA1、SHA256、SHA512 等。

package main

import ( "crypto/sha256" "fmt" )

func hashData(data []byte) []byte { h := sha256.New() h.Write(data) return h.Sum(nil) }

// 示例 func main() { data := []byte("hello world") hash := hashData(data) fmt.Printf("SHA256: %x\n", hash) }

提示: 存储密码时建议使用 golang.org/x/crypto/bcrypt,而非原始哈希。

消息认证码:使用HMAC验证数据完整性

HMAC结合密钥和哈希算法,确保消息未被篡改。

适用场景: API签名、Token验证等。

package main

import ( "crypto/hmac" "crypto/sha256" )

func signMessage(message, key []byte) []byte { mac := hmac.New(sha256.New, key) mac.Write(message) return mac.Sum(nil) }

func verifyMessage(message, key, expectedMAC []byte) bool { mac := hmac.New(sha256.New, key) mac.Write(message) actual := mac.Sum(nil) return hmac.Equal(actual, expectedMAC) }

关键点: 使用 hmac.Equal 进行比较以防止时序攻击。

基本上就这些。掌握这些基础操作后,可以根据实际需求组合使用,比如用RSA加密AES密钥,再用AES加密数据,实现混合加密系统。安全编码中务必注意密钥管理、随机数来源和填充模式的选择。