
数字签名是现代密码学中的一项关键技术,用于验证数字信息的真实性、完整性和不可否认性。它通过使用发送者的私钥对消息的哈希值进行加密,生成一个独特的签名。接收者可以使用发送者的公钥解密签名,并与自己计算的消息哈希值进行比对,从而确认消息来源的合法性以及消息在传输过程中是否被篡改。
Go语言的crypto/rsa包提供了RSA算法的实现,包括密钥生成、加密、解密以及数字签名和验证功能。其中,SignPKCS1v15和VerifyPKCS1v15函数是基于PKCS#1 v1.5标准的签名方案,广泛应用于各种安全通信场景。
在进行数字签名之前,首先需要生成一对RSA密钥:私钥(Private Key)用于签名,公钥(Public Key)用于验证。
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"log"
"os"
)
// generateRSAKeyPair 生成指定位数的RSA密钥对
func generateRSAKeyPair(bits int) (*rsa.PrivateKey, *rsa.PublicKey, error) {
privateKey, err := rsa.GenerateKey(rand.Reader, bits)
if err != nil {
return nil, nil, fmt.Errorf("failed to generate RSA private key: %w", err)
}
return privateKey, &privateKey.PublicKey, nil
}
// savePrivateKeyToPEM 将私钥保存为PEM格式文件
func savePrivateKeyToPEM(privateKey *rsa.PrivateKey, filename string) error {
privatePEM := &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
}
return os.WriteFile(filename, pem.EncodeToMemory(privatePEM), 0600)
}
// savePublicKeyToPEM 将公钥保存为PEM格式文件
func savePublicKeyToPEM(publicKey *rsa.PublicKey, filename string) error {
publicKeyBytes, err := x509.MarshalPKIXPublicKey(publicKey)
if err != nil {
return fmt.Errorf("failed to marshal public key: %w", err)
}
publicPEM := &pem.Block{
Type: "PUBLIC KEY",
Bytes: publicKeyBytes,
}
return os.WriteFile(filename, pem.EncodeToMemory(publicPEM), 0644)
}
func main() {
// 生成2048位的RSA密钥对
privateKey, publicKey, err := generateRSAKeyPair(2048)
if err != nil {
log.Fatalf("Error generating keys: %v", err)
}
fmt.Println("RSA密钥对生成成功。")
// 示例:将密钥保存到文件
if err := savePrivateKeyToPEM(privateKey, "private.pem"); err != nil {
log.Fatalf("Error saving private key: %v", err)
}
if err := savePublicKeyToPEM(publicKey, "public.pem"); err != nil {
log.Fatalf("Error saving public key: %v", err)
}
fmt.Println("私钥已保存到 private.pem,公钥已保存到 public.pem")
// 实际应用中,你可能需要从文件中加载密钥
// loadPrivateKeyFromPEM("private.pem")
// loadPublicKeyFromPEM("public.pem")
}说明:
立即学习“go语言免费学习笔记(深入)”;
数字签名并非直接作用于原始消息,而是作用于消息的哈希值。这样做有几个优点:
在Go语言中,可以使用crypto包下的各种哈希算法(如sha256、sha512等)来计算消息的哈希值。
import (
"crypto/sha256"
"encoding/json"
// ... 其他导入
)
// ExampleMessage 代表待签名的结构体消息
type ExampleMessage struct {
ID string `json:"id"`
Content string `json:"content"`
Timestamp int64 `json:"timestamp"`
}
// hashMessage 计算消息的SHA256哈希值
func hashMessage(msg ExampleMessage) ([]byte, error) {
// 将结构体序列化为字节切片
messageBytes, err := json.Marshal(msg)
if err != nil {
return nil, fmt.Errorf("failed to marshal message: %w", err)
}
// 计算SHA256哈希
hashed := sha256.Sum256(messageBytes)
return hashed[:], nil // 返回字节切片
}说明:
立即学习“go语言免费学习笔记(深入)”;
rsa.SignPKCS1v15函数用于使用私钥对消息的哈希值进行签名。
func SignPKCS1v15(rand io.Reader, priv *PrivateKey, hash crypto.Hash, hashed []byte) ([]byte, error)
参数解释:
示例代码:
package main
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"encoding/json"
"fmt"
"log"
"time"
)
// ExampleMessage 代表待签名的结构体消息
type ExampleMessage struct {
ID string `json:"id"`
Content string `json:"json"`
Timestamp int64 `json:"timestamp"`
}
func main() {
// 1. 生成RSA密钥对
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
log.Fatalf("Failed to generate RSA private key: %v", err)
}
publicKey := &privateKey.PublicKey
fmt.Println("RSA密钥对生成成功。")
// 2. 待签名消息
message := ExampleMessage{
ID: "order-12345",
Content: "Client ordered 5 units of product X.",
Timestamp: time.Now().Unix(),
}
// 3. 序列化消息并计算哈希值
messageBytes, err := json.Marshal(message)
if err != nil {
log.Fatalf("Failed to marshal message: %v", err)
}
fmt.Printf("原始消息 (JSON): %s\n", string(messageBytes))
hashed := sha256.Sum256(messageBytes)
fmt.Printf("消息哈希 (SHA256): %x\n", hashed[:])
// 4. 使用SignPKCS1v15进行签名
// 参数:rand.Reader (随机源), privateKey (私钥), crypto.SHA256 (哈希算法标识), hashed[:] (哈希值)
signature, err := rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA256, hashed[:])
if err != nil {
log.Fatalf("Failed to sign message: %v", err)
}
fmt.Printf("数字签名: %x\n", signature)
// ... 接下来进行验签
}rsa.VerifyPKCS1v15函数用于使用公钥验证数字签名的有效性。
func VerifyPKCS1v15(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte) error
参数解释:
示例代码(接上文):
package main
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"encoding/json"
"fmt"
"log"
"time"
)
// ExampleMessage 代表待签名的结构体消息
type ExampleMessage struct {
ID string `json:"id"`
Content string `json:"content"`
Timestamp int64 `json:"timestamp"`
}
func main() {
// 1. 生成RSA密钥对
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
log.Fatalf("Failed to generate RSA private key: %v", err)
}
publicKey := &privateKey.PublicKey
fmt.Println("RSA密钥对生成成功。")
// 2. 待签名消息
message := ExampleMessage{
ID: "order-12345",
Content: "Client ordered 5 units of product X.",
Timestamp: time.Now().Unix(),
}
// 3. 序列化消息并计算哈希值
messageBytes, err := json.Marshal(message)
if err != nil {
log.Fatalf("Failed to marshal message: %v", err)
}
fmt.Printf("原始消息 (JSON): %s\n", string(messageBytes))
hashed := sha256.Sum256(message以上就是Go语言中RSA数字签名的实现与应用:PKCS#1 v1.5标准详解的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号