首页 > 后端开发 > Golang > 正文

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

P粉602998670
发布: 2025-11-21 09:07:02
原创
165人浏览过
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)。

立即学习go语言免费学习笔记(深入)”;

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

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

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

知我AI
知我AI

一款多端AI知识助理,通过一键生成播客/视频/文档/网页文章摘要、思维导图,提高个人知识获取效率;自动存储知识,通过与知识库聊天,提高知识利用效率。

知我AI 101
查看详情 知我AI
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 包设计清晰,配合标准库使用非常方便。只要注意密钥管理、模式选择和随机数安全,就能构建基本的安全通信机制。

以上就是Golang如何使用 crypto 包实现加密算法_Golang crypto 数据加密与解密方法的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号