登录
首页 >  Golang >  Go教程

Golangcrypto加密实战教程详解

时间:2026-01-06 17:25:38 361浏览 收藏

各位小伙伴们,大家好呀!看看今天我又给各位带来了什么文章?本文标题《Golang crypto包加密实战教程》,很明显是关于Golang的文章哈哈哈,其中内容主要会涉及到等等,如果能帮到你,觉得很不错的话,欢迎各位多多点评和分享!

Go语言crypto包支持SHA-256哈希、AES对称加密和RSA非对称加密;通过sha256.Sum256计算摘要,aes.NewCipher配合cipher.NewCBCEncrypter实现AES加密,rsa.GenerateKey生成密钥对并使用EncryptPKCS1v15进行RSA加密,适用于数据安全、完整性校验与密钥交换场景。

Golang如何使用crypto包实现加密_Golang crypto加密实践

Go语言的crypto包提供了多种加密算法的支持,包括对称加密、非对称加密、哈希函数和数字签名等。实际开发中,合理使用这些工具能有效保障数据安全。下面通过常见场景说明如何在Golang中使用crypto包进行加密操作。

使用crypto/sha256生成消息摘要

SHA-256是常用的哈希算法,适用于密码存储、数据完整性校验等场景。

示例:计算字符串的SHA-256值

代码实现:
使用sha256.Sum256()可以直接得到[32]byte类型的摘要,转为十六进制字符串便于展示。

package main

import (
  "crypto/sha256"
  "fmt"
)

func main() {
  data := []byte("hello world")
  hash := sha256.Sum256(data)
  fmt.Printf("%x\n", hash) // 输出: b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9
}

使用crypto/aes进行AES对称加密

AES(高级加密标准)是最广泛使用的对称加密算法之一,适合加密大量数据。

关键点:
需要密钥长度为16、24或32字节(分别对应AES-128、AES-192、AES-256),并选择合适的加密模式如CBC或GCM。

示例:使用AES-CBC模式加密字符串

package main

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

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

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

  mode := cipher.NewCBCEncrypter(block, iv)
  mode.CryptBlocks(ciphertext[blockSize:], plaintext)
  return ciphertext, nil
}

func pad(data []byte, blockSize int) []byte {
  padding := blockSize - len(data)%blockSize
  padtext := make([]byte, padding)
  for i := range padtext {
    padtext[i] = byte(padding)
  }
  return append(data, padtext...)
}

func main() {
  key := []byte("example key 1234") // 16字节密钥
  plaintext := []byte("this is a secret message")
  ciphertext, _ := encrypt(plaintext, key)
  fmt.Printf("Encrypted: %x\n", ciphertext)
}

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

RSA常用于安全通信中的密钥交换或数字签名,公钥加密,私钥解密。

示例:生成RSA密钥并对数据加密

说明:
使用rsa.GenerateKey生成密钥对,利用公钥加密,私钥可后续用于解密。

package main

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

func generateRSAKey() {
  privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
  if err != nil {
    panic(err)
  }

  derStream := x509.MarshalPKCS1PrivateKey(privateKey)
  block := &pem.Block{
    Type: "RSA PRIVATE KEY",
    Bytes: derStream,
  }
  pemfile, _ := os.Create("private.pem")
  pem.Encode(pemfile, block)
  pemfile.Close()

  publicKey := &privateKey.PublicKey
  pubDer, _ := x509.MarshalPKIXPublicKey(publicKey)
  pubBlock := &pem.Block{
    Type: "PUBLIC KEY",
    Bytes: pubDer,
  }
  pubFile, _ := os.Create("public.pem")
  pem.Encode(pubFile, pubBlock)
  pubFile.Close()
}

func encryptWithPubKey(msg []byte, pub *rsa.PublicKey) ([]byte, error) {
  return rsa.EncryptPKCS1v15(rand.Reader, pub, msg)
}

func main() {
  generateRSAKey()
  fmt.Println("RSA密钥已生成")
}

上述代码会生成private.pem和public.pem两个文件,可用于后续加解密流程。

基本上就这些常见用法。实际项目中注意密钥管理、填充模式选择以及避免硬编码敏感信息。crypto包设计严谨,配合标准库使用非常方便。

终于介绍完啦!小伙伴们,这篇关于《Golangcrypto加密实战教程详解》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

前往漫画官网入口并下载 ➜
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>