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

Golang crypto加密解密操作示例

P粉602998670
发布: 2025-09-28 22:18:01
原创
191人浏览过
Go语言crypto包支持AES和RSA加密。首先介绍AES-GCM模式加解密,使用16字节密钥对数据进行加密并Base64编码;接着演示RSA非对称加密,生成2048位密钥对,公钥加密、私钥解密,并支持PEM格式保存与加载密钥,确保实际应用中的密钥管理安全。

golang crypto加密解密操作示例

Go语言的crypto包提供了多种加密和解密功能,常用于数据安全传输和存储。下面介绍几种常见的加密方式:AES对称加密和RSA非对称加密,并给出可运行的示例代码。

AES对称加密(CBC模式)

AES是一种对称加密算法,加密和解密使用相同的密钥。以下是使用AES-CBC模式进行加密和解密的示例:

说明: 需要密钥长度为16、24或32字节(对应AES-128、AES-192、AES-256),并使用PKCS7填充。

示例代码:

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

package main

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

func aesEncrypt(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 aesDecrypt(ciphertext string, key []byte) ([]byte, error) {
    data, err := base64.StdEncoding.DecodeString(ciphertext)
    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字节密钥
    message := []byte("Hello, this is a secret message!")

    encrypted, err := aesEncrypt(message, key)
    if err != nil {
        panic(err)
    }
    fmt.Println("Encrypted:", encrypted)

    decrypted, err := aesDecrypt(encrypted, key)
    if err != nil {
        panic(err)
    }
    fmt.Println("Decrypted:", string(decrypted))
}
登录后复制

RSA非对称加密

RSA是一种非对称加密算法,使用公钥加密,私钥解密。适合小数据加密或密钥交换。

说明: Go中可通过crypto/rsa和crypto/rand生成密钥对,使用公钥加密,私钥解密。

Felvin
Felvin

AI无代码市场,只需一个提示快速构建应用程序

Felvin 161
查看详情 Felvin

示例代码:

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

package main

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

func generateRSAKeys() (*rsa.PrivateKey, *rsa.PublicKey, error) {
    privatekey, err := rsa.GenerateKey(rand.Reader, 2048)
    if err != nil {
        return nil, nil, err
    }
    publickey := &privatekey.PublicKey
    return privatekey, publickey, nil
}

func rsaEncrypt(plaintext []byte, pub *rsa.PublicKey) ([]byte, error) {
    ciphertext, err := rsa.EncryptPKCS1v15(rand.Reader, pub, plaintext)
    return ciphertext, err
}

func rsaDecrypt(ciphertext []byte, priv *rsa.PrivateKey) ([]byte, error) {
    plaintext, err := rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
    return plaintext, err
}

func main() {
    // 生成密钥对
    privKey, pubKey, err := generateRSAKeys()
    if err != nil {
        log.Fatal(err)
    }

    message := []byte("Secret message for RSA encryption")

    // 加密
    encrypted, err := rsaEncrypt(message, pubKey)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("Encrypted (base64):", base64.StdEncoding.EncodeToString(encrypted))

    // 解密
    decrypted, err := rsaDecrypt(encrypted, privKey)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("Decrypted:", string(decrypted))
}
登录后复制

保存和加载PEM格式密钥

在实际应用中,通常需要将RSA密钥保存到文件或从文件读取。PEM是常用格式。

保存私钥和公钥到PEM:

// 保存私钥
func savePrivateKey(priv *rsa.PrivateKey) []byte {
    privBytes := x509.MarshalPKCS1PrivateKey(priv)
    privPem := pem.EncodeToMemory(&pem.Block{
        Type:  "RSA PRIVATE KEY",
        Bytes: privBytes,
    })
    return privPem
}

// 保存公钥
func savePublicKey(pub *rsa.PublicKey) []byte {
    pubBytes, _ := x509.MarshalPKIXPublicKey(pub)
    pubPem := pem.EncodeToMemory(&pem.Block{
        Type:  "PUBLIC KEY",
        Bytes: pubBytes,
    })
    return pubPem
}
登录后复制

从PEM加载密钥:

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

func loadPublicKey(pemData []byte) (*rsa.PublicKey, error) {
    block, _ := pem.Decode(pemData)
    pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
    if err != nil {
        return nil, err
    }
    return pubInterface.(*rsa.PublicKey), nil
}
登录后复制

基本上就这些。通过crypto包可以实现常见加密需求,注意密钥安全管理和填充模式选择。实际项目中建议结合TLS或成熟加密库使用。

以上就是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号