一、Go基础知识39、加密解密:crypto 包

在Go语言中,crypto包提供了许多加密和解密算法的实现,包括对称加密、非对称加密、哈希函数等。

一、对称加密(AES算法)

1、加密数据

package main

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

func main() {
	// 生成随机密钥
	key := make([]byte, 32)
	if _, err := rand.Read(key); err != nil {
		panic(err)
	}

	plaintext := []byte("Hello, AES!")

	// 创建AES加密块
	block, err := aes.NewCipher(key)
	if err != nil {
		panic(err)
	}

	// 使用CTR模式进行加密
	ciphertext := make([]byte, aes.BlockSize+len(plaintext))
	iv := ciphertext[:aes.BlockSize]
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		panic(err)
	}

	stream := cipher.NewCTR(block, iv)
	stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)

	fmt.Printf("Plaintext: %s\n", plaintext)
	fmt.Printf("Ciphertext: %x\n", ciphertext)
}

解释
这个例子中,使用AES算法对字符串 “Hello, AES!” 进行加密。生成随机密钥,使用CTR模式创建加密块,然后对明文进行加密。

2、解密数据

package main

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

func main() {
	// 密钥和密文,这些数据通常由加密方提供
	key := []byte("32-byte-key-1234567890123456")
	ciphertext, _ := hex.DecodeString("9c630d74f7e69e13af22")

	// 创建AES解密块
	block, err := aes.NewCipher(key)
	if err != nil {
		panic(err)
	}

	// 提取初始化向量
	iv := ciphertext[:aes.BlockSize]
	ciphertext = ciphertext[aes.BlockSize:]

	// 使用CTR模式进行解密
	stream := cipher.NewCTR(block, iv)
	stream.XORKeyStream(ciphertext, ciphertext)

	fmt.Printf("Decrypted: %s\n", ciphertext)
}

解释
这个例子中,使用相同的密钥和初始化向量对加密后的数据进行解密,得到原始的明文。

二、非对称加密(RSA算法)

1、加密数据

package main

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

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

	// 对公钥进行编码
	publicKey := &privateKey.PublicKey
	pubBytes, err := x509.MarshalPKIXPublicKey(publicKey)
	if err != nil {
		panic(err)
	}
	pubBlock := &pem.Block{
		Type:  "PUBLIC KEY",
		Bytes: pubBytes,
	}
	pubPEM := pem.EncodeToMemory(pubBlock)

	plaintext := []byte("Hello, RSA!")

	// 使用公钥进行加密
	ciphertext, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, plaintext)
	if err != nil {
		panic(err)
	}

	fmt.Printf("Plaintext: %s\n", plaintext)
	fmt.Printf("Ciphertext: %x\n", ciphertext)
	fmt.Printf("Public Key: %s\n", pubPEM)
}

解释
这个例子中,使用RSA算法生成密钥对,然后使用公钥对字符串 “Hello, RSA!” 进行加密。

2、解密数据

package main

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

func main() {
	// 公钥、私钥和密文,这些数据通常由加密方提供
	pubPEM := []byte("-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwDA6lr1fTIfkzhq3XwWU\n... (公钥内容) ...")
	ciphertext, _ := hex.DecodeString("c6e3aa3ea813598784d1")

	// 解码公钥
	block, _ := pem.Decode(pubPEM)
	if block == nil || block.Type != "PUBLIC KEY" {
		panic("failed to decode PEM block containing public key")
	}
	pub, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		panic(err)
	}

	// 使用私钥进行解密
	plaintext, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, ciphertext)
	if err != nil {
		panic(err)
	}

	fmt.Printf("Decrypted: %s\n", plaintext)
}

解释
这个例子中,使用相同的私钥和公钥对加密后的数据进行解密,得到原始的明文。

三、哈希函数(SHA-256算法)

计算哈希值

package main

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

func main() {
	data := []byte("Hello, SHA-256!")

	// 创建SHA-256哈希对象
	hash := sha256.New()

	// 写入数据并计算哈希值
	hash.Write(data)
	hashValue := hash.Sum(nil)

	fmt.Printf("Data: %s\n", data)
	fmt.Printf("SHA-256 Hash: %s\n", hex.EncodeToString(hashValue))
}

解释
这个例子中,使用SHA-256算法计算字符串 “Hello, SHA-256!” 的哈希值。

四、数字签名(RSA算法)

1、签名数据

package main

import (
	"crypto"
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
)

func main() {
	// 使用之前例子中生成的私钥
	privateKey, _ := rsa.GenerateKey(rand.Reader, 2048)

	data := []byte("Hello, Digital Signature!")

	// 创建SHA-256哈希对象
	hash := sha256.New()

	// 写入数据并计算哈希值
	hash.Write(data)
	hashValue := hash.Sum(nil)

	// 使用私钥进行数字签名
	signature, err := rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA256, hashValue)
	if err != nil {
		panic(err)
	}

	fmt.Printf("Data: %s\n", data)
	fmt.Printf("Digital Signature: %s\n", hex.EncodeToString(signature))
}

解释
这个例子中,使用RSA算法和SHA-256哈希计算对字符串 “Hello, Digital Signature!” 进行数字签名。

2、验证数字签名

package main

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

func main() {
	// 使用之前例子中生成的公钥和签名
	pubPEM := []byte("-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwDA6lr1fTIfkzhq3XwWU\n... (公钥内容) ...")
	signature, _ := hex.DecodeString("5a143dca8dfc656c9a7")

	// 解码公钥
	block, _ := pem.Decode(pubPEM)
	if block == nil || block.Type != "PUBLIC KEY" {
		panic("failed to decode PEM block containing public key")
	}
	pub, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		panic(err)
	}

	// 创建SHA-256哈希对象
	hash := sha256.New()

	// 写入数据并计算哈希值
	hash.Write(data)
	hashValue := hash.Sum(nil)

	// 使用公钥验证数字签名
	err = rsa.VerifyPKCS1v15(pub.(*rsa.PublicKey), crypto.SHA256, hashValue, signature)
	if err != nil {
		fmt.Println("Signature verification failed.")
	} else {
		fmt.Println("Signature verified successfully.")
	}
}

解释
这个例子中,使用相同的哈希算法和公钥对数字签名进行验证。

  • 12
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风不归Alkaid

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值