登录
首页 >  Golang >  Go教程

Golangcrypto加密教程全解析

时间:2025-10-23 17:25:29 127浏览 收藏

本文详细解读Golang `crypto`包的加密应用,提供AES对称加密、RSA非对称加密以及SHA-256哈希值生成的实用教程。针对AES加密,重点讲解了使用`crypto/aes`包进行CBC模式加密,强调随机IV生成的重要性,并提供`NewCBCEncrypter`和`NewCBCDecrypter`的示例代码,助力开发者理解加密解密流程。同时,深入探讨RSA在密钥交换和少量数据加密中的应用,并介绍了使用`crypto/rsa`生成密钥对及加解密的方法。最后,介绍了如何利用`crypto/sha256`生成哈希值,用于数据完整性校验,并提醒密码存储时应使用更安全的哈希算法。掌握这些技巧,能有效提升Golang应用的数据安全防护能力。

使用crypto/aes进行AES对称加密,需选择CBC模式并生成随机IV,加密时填充密文并使用NewCBCEncrypter,解密时用NewCBCDecrypter还原明文。

如何在Golang中使用crypto包进行加密

在Golang中,crypto包提供了多种加密算法的实现,可用于数据安全保护。要正确使用它,需根据具体需求选择合适的子包,如AES对称加密、RSA非对称加密或生成哈希值等。

使用crypto/aes进行对称加密

AES(高级加密标准)是常用的对称加密方式,加密和解密使用相同密钥。

以下是使用CBC模式进行AES加密的示例:

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)

    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) 

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

使用crypto/rsa进行非对称加密

RSA适合加密小量数据或传输对称密钥。

生成密钥对并加密示例:

package main

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

// 生成RSA私钥
func generatePrivateKey() (*rsa.PrivateKey, error) {
    return rsa.GenerateKey(rand.Reader, 2048)
}

// 导出为PEM格式
func encodePrivateKey(key *rsa.PrivateKey) []byte {
    privBytes := x509.MarshalPKCS1PrivateKey(key)
    return pem.EncodeToMemory(&pem.Block{
        Type:  "RSA PRIVATE KEY",
        Bytes: privBytes,
    })
}

// 使用公钥加密
func encryptWithPublicKey(msg []byte, pub *rsa.PublicKey) ([]byte, error) {
    return rsa.EncryptPKCS1v15(rand.Reader, pub, msg)
}

// 使用私钥解密
func decryptWithPrivateKey(ciphertext []byte, priv *rsa.PrivateKey) ([]byte, error) {
    return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
}

实际使用中,通常结合对称与非对称加密,例如用RSA加密AES密钥。

使用crypto/sha256生成哈希值

SHA-256常用于数据完整性校验。

package main

import (
    "crypto/sha256"
    "fmt"
)

func hashData(data []byte) []byte {
    h := sha256.Sum256(data)
    return h[:]
}

// 示例
func main() {
    data := []byte("hello world")
    hash := hashData(data)
    fmt.Printf("%x\n", hash) // 输出十六进制哈希
}

该操作不可逆,适用于密码哈希存储(但建议使用bcrypt或scrypt增强安全性)。

基本上就这些。根据场景选择合适算法,注意密钥管理与初始化向量(IV)的随机性,避免重复使用IV,确保加密安全性。

今天关于《Golangcrypto加密教程全解析》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

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