登录
首页 >  Golang >  Go教程

Golangcrypto加密解密方法全解析

时间:2025-12-04 22:15:39 180浏览 收藏

推广推荐
免费电影APP ➜
支持 PC / 移动端,安全直达

本文深入解析了 Golang `crypto` 包在加密解密中的应用,重点讲解了 AES 对称加密、RSA 非对称加密以及 HMAC-SHA256 消息认证等常用方法。通过代码示例,详细展示了如何使用 `crypto/aes` 实现 AES-GCM 加解密,强调了密钥长度的重要性及 GCM 模式的安全性优势;同时,也演示了 `crypto/rsa` 生成密钥对并进行加解密的过程,并提醒 RSA 适用于加密少量数据或传输对称密钥;此外,文章还介绍了如何使用 `crypto/sha256` 和 `crypto/hmac` 进行哈希与消息认证,保障数据完整性。掌握这些 `crypto` 包的使用技巧,能帮助开发者构建更安全的 Golang 应用。

Go语言crypto包提供AES、RSA、SHA256等加密功能,示例展示AES-GCM对称加解密、RSA非对称加解密及HMAC-SHA256消息认证,强调安全模式与密钥管理。

Golang如何使用 crypto 包实现加密算法_Golang crypto 数据加密与解密方法

Go语言的 crypto 包为常见的加密算法提供了标准接口和实现,广泛用于数据加密、解密、签名和哈希计算等安全场景。通过合理使用 crypto 包中的子包(如 crypto/aes、crypto/des、crypto/rsa、crypto/rand 等),可以高效实现对称加密、非对称加密以及安全随机数生成。

使用 crypto/aes 实现 AES 对称加密与解密

AES(Advanced Encryption Standard)是最常用的对称加密算法之一,支持 128、192 和 256 位密钥长度。Go 中通过 crypto/aescrypto/cipher 包实现 AES 加密。

常见模式使用 CBC(Cipher Block Chaining)或 GCM(Galois/Counter Mode),以下是一个使用 AES-CBC 的示例:

package main

import (
    "crypto/aes"
    "crypto/cipher"
    "crypto/rand"
    "encoding/base64"
    "fmt"
    "io"
)

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

    gcm, err := cipher.NewGCM(block)
    if err != nil {
        return "", err
    }

    nonce := make([]byte, gcm.NonceSize())
    if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
        return "", err
    }

    ciphertext := gcm.Seal(nonce, nonce, plaintext, nil)
    return base64.StdEncoding.EncodeToString(ciphertext), nil
}

func decrypt(ciphertextStr string, key []byte) ([]byte, error) {
    data, err := base64.StdEncoding.DecodeString(ciphertextStr)
    if err != nil {
        return nil, err
    }

    block, err := aes.NewCipher(key)
    if err != nil {
        return nil, err
    }

    gcm, err := cipher.NewGCM(block)
    if err != nil {
        return nil, err
    }

    nonceSize := gcm.NonceSize()
    if len(data) < nonceSize {
        return nil, fmt.Errorf("ciphertext too short")
    }

    nonce, ciphertext := data[:nonceSize], data[nonceSize:]
    return gcm.Open(nil, nonce, ciphertext, nil)
}

func main() {
    key := []byte("example key 1234") // 16字节密钥(AES-128)
    plaintext := []byte("Hello, this is a secret message!")

    encrypted, err := encrypt(plaintext, key)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Encrypted: %s\n", encrypted)

    decrypted, err := decrypt(encrypted, key)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Decrypted: %s\n", decrypted)
}

说明:该示例使用 AES-GCM 模式,它提供认证加密(AEAD),比 CBC 更安全且无需单独处理填充。密钥必须是 16、24 或 32 字节(对应 AES-128/192/256)。

使用 crypto/rsa 实现 RSA 非对称加密

RSA 是一种非对称加密算法,适用于加密小量数据或传输对称密钥。Go 的 crypto/rsa 结合 crypto/rand 可实现公钥加密、私钥解密。

以下演示如何生成密钥对并进行加解密:

package main

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

func main() {
    // 生成 RSA 密钥对(2048位)
    privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
    if err != nil {
        panic(err)
    }

    // 获取公钥
    publicKey := &privateKey.PublicKey

    plaintext := []byte("This is a secret message only for RSA.")

    // 使用公钥加密
    ciphertext, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, plaintext)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Encrypted (base64): %s\n", 
        base64.StdEncoding.EncodeToString(ciphertext))

    // 使用私钥解密
    decrypted, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, ciphertext)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Decrypted: %s\n", decrypted)
}

注意:RSA 只适合加密小于密钥长度的数据(减去填充)。实际应用中常用于加密 AES 密钥,而非原始数据。

使用 crypto/sha256 和 crypto/hmac 进行哈希与消息认证

数据完整性验证常使用 SHA-256 哈希和 HMAC 签名。Go 的 crypto/sha256crypto/hmac 提供了简单接口。

示例:计算字符串 SHA256 哈希和 HMAC-SHA256:

package main

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

func main() {
    data := "hello world"
    key := []byte("my-secret-key")

    // SHA256 哈希
    hash := sha256.Sum256([]byte(data))
    fmt.Printf("SHA256: %s\n", hex.EncodeToString(hash[:]))

    // HMAC-SHA256
    h := hmac.New(sha256.New, key)
    h.Write([]byte(data))
    mac := h.Sum(nil)
    fmt.Printf("HMAC-SHA256: %s\n", hex.EncodeToString(mac))
}

HMAC 可防止哈希被篡改,常用于 API 签名、Token 验证等场景。

基本上就这些常用方法。Go 的 crypto 包设计清晰,配合标准库使用非常方便。只要注意密钥管理、模式选择和随机数安全,就能构建基本的安全通信机制。

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《Golangcrypto加密解密方法全解析》文章吧,也可关注golang学习网公众号了解相关技术文章。

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>