
本教程详细阐述了在go语言中安全验证aws sns消息签名的过程。我们将探讨签名验证的核心原理,包括规范化字符串、哈希生成与断言,并指出手动实现中常见的挑战。最终,推荐并演示如何利用现有的go.sns库高效、可靠地完成签名验证,确保消息的真实性和完整性。
AWS Simple Notification Service (SNS) 是一种高度可用的、灵活的、完全托管的发布/订阅消息服务。当SNS将消息发送到HTTP/S端点时,为了确保消息的真实性和完整性,AWS会对消息进行数字签名。作为消息接收方,对这些签名进行验证至关重要,它可以防止未经授权的第三方篡改消息内容或伪造消息来源,从而保障应用程序的安全性。
AWS SNS的签名验证过程遵循标准的数字签名机制,涉及以下几个核心步骤:
构建规范化字符串 (Canonical String) 接收到的SNS消息是一个JSON对象。在进行签名之前,AWS会根据消息中的特定字段(Message、MessageId、Subject、Timestamp、TopicArn、Type等)以特定顺序和格式构建一个“规范化字符串”。这个字符串是签名计算的原始输入。
例如,一个规范化字符串的结构可能如下所示:
Message Hello from SNS! MessageId a1b2c3d4-e5f6-7890-1234-567890abcdef Subject My Subject Timestamp 2023-10-27T12:00:00.000Z TopicArn arn:aws:sns:us-east-1:123456789012:MyTopic Type Notification
请注意,如果Subject字段不存在,则在规范化字符串中不应包含Subject及其值。
立即学习“go语言免费学习笔记(深入)”;
生成派生哈希值 (Derived Hash Value) 这是指接收方对本地构建的规范化字符串进行哈希运算。AWS SNS通常使用SHA1或SHA256哈希算法,具体取决于消息中的SignatureVersion字段(版本1通常使用SHA1)。这个哈希值代表了消息内容的“指纹”。
生成断言哈希值 (Asserted Hash Value) SNS消息中包含一个Signature字段,这是一个Base64编码的字符串,它是AWS使用其私钥对规范化字符串的哈希值进行加密(签名)后的结果。断言哈希值是通过以下步骤获得的:
验证过程 将步骤2中生成的派生哈希值与步骤3中生成的断言哈希值进行比较。如果两者完全一致,则表明消息未被篡改,且确实由AWS SNS发送。
在Go语言中手动实现SNS签名验证,需要处理网络请求、证书解析、哈希计算和RSA签名验证等多个环节。以下是具体步骤及常见问题解析:
构建规范化字符串 根据上述原理,需要根据SNS消息结构动态构建字符串。
package main
import (
"fmt"
"strings"
)
// 假设这是SNS消息的简化结构
type Notification struct {
Message string
MessageId string
Signature string
SignatureVersion string
SigningCertURL string
SubscribeURL string
Subject string
Timestamp string
TopicArn string
Type string
UnsubscribeURL string
}
// buildCanonicalString 根据SNS消息构建规范化字符串
func (n *Notification) buildCanonicalString() string {
var sb strings.Builder
sb.WriteString("Message\n")
sb.WriteString(n.Message)
sb.WriteString("\nMessageId\n")
sb.WriteString(n.MessageId)
if n.Subject != "" {
sb.WriteString("\nSubject\n")
sb.WriteString(n.Subject)
}
sb.WriteString("\nTimestamp\n")
sb.WriteString(n.Timestamp)
sb.WriteString("\nTopicArn\n")
sb.WriteString(n.TopicArn)
sb.WriteString("\nType\n")
sb.WriteString(n.Type)
return sb.String()
}获取签名证书与公钥 从SigningCertURL下载PEM格式的证书,然后解析为X.509证书并提取RSA公钥。
import (
"crypto/x509"
"encoding/pem"
"io/ioutil"
"net/http"
"crypto/rsa"
)
func getPublicKey(certURL string) (*rsa.PublicKey, error) {
resp, err := http.Get(certURL)
if err != nil {
return nil, fmt.Errorf("failed to download certificate: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("failed to download certificate, status code: %d", resp.StatusCode)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read certificate body: %w", err)
}
p, _ := pem.Decode(body)
if p == nil {
return nil, fmt.Errorf("failed to decode PEM block from certificate")
}
cert, err := x509.ParseCertificate(p.Bytes)
if err != nil {
return nil, fmt.Errorf("failed to parse X.509 certificate: %w", err)
}
publicKey, ok := cert.PublicKey.(*rsa.PublicKey)
if !ok {
return nil, fmt.Errorf("certificate public key is not RSA")
}
return publicKey, nil
}解码签名与计算规范化字符串哈希 将Base64编码的签名解码,并对规范化字符串进行哈希。SNS SignatureVersion: 1通常使用SHA1。
import (
"encoding/base64"
"crypto/sha1"
"crypto" // For crypto.SHA1
)
func decodeSignatureAndHashCanonical(notification *Notification) ([]byte, []byte, error) {
decodedSignature, err := base64.StdEncoding.DecodeString(notification.Signature)
if err != nil {
return nil, nil, fmt.Errorf("failed to base64 decode signature: %w", err)
}
canonicalString := notification.buildCanonicalString()
hasher := sha1.New() // For SignatureVersion 1, use SHA1
hasher.Write([]byte(canonicalString))
hashedCanonicalString := hasher.Sum(nil)
return decodedSignature, hashedCanonicalString, nil
}执行签名验证 这是最容易出错的步骤。原问题中尝试使用cert.CheckSignature(x509.SHA1WithRSA, signed, []byte(signString)),这个方法是用于验证证书本身的签名(即验证证书是否由其颁发者签名),而不是用于验证任意消息的签名。
正确的做法是使用rsa.VerifyPKCS1v15函数,它需要公钥、哈希算法标识、消息的哈希值和签名值。
// ... (previous imports)
import "crypto/rsa"
func verifySNSSignature(notification *Notification) error {
publicKey, err := getPublicKey(notification.SigningCertURL)
if err != nil {
return fmt.Errorf("failed to get public key: %w", err)
}
decodedSignature, hashedCanonicalString, err := decodeSignatureAndHashCanonical(notification)
if err != nil {
return fmt.Errorf("failed to prepare for verification: %w", err)
}
// 对于 SignatureVersion 1,通常使用 SHA1 和 PKCS1v15 填充
err = rsa.VerifyPKCS1v1v5(publicKey, crypto.SHA1, hashedCanonicalString, decodedSignature)
if err != nil {
return fmt.Errorf("signature verification failed: %w", err)
}
return nil // Signature is valid
}鉴于手动实现SNS签名验证涉及的复杂性和潜在错误,强烈建议使用经过社区验证的第三方库。github.com/robbiet480/go.sns库就是这样一个优秀的选择,它封装了所有必要的逻辑,大大简化了验证过程。
安装go.sns库
go get github.com/robbiet480/go.sns
使用示例
该库提供了一个简洁的API来处理SNS消息的JSON解析和签名验证。
package main
import (
"encoding/json"
"fmt"
"log"
"github.com/robbiet480/go.sns"
)
func main() {
// 假设 notificationJson 是从SNS接收到的原始JSON字符串
// 在实际应用中,这通常来自HTTP请求的请求体
notificationJson := `{
"Type" : "Notification",
"MessageId" : "a1b2c3d4-e5f6-7890-1234-567890abcdef",
"TopicArn" : "arn:aws:sns:us-east-1:123456789012:MyTopic",
"Subject" : "My Subject",
"Message" : "Hello from SNS!",
"Timestamp" : "2023-10-27T12:00:00.000Z",
"SignatureVersion" : "1",
"Signature" : "YOUR_BASE64_ENCODED_SNS_SIGNATURE_HERE",
"SigningCertURL" : "https://sns.us-east-1.amazonaws.com/SimpleNotificationService.pem",
"UnsubscribeURL" : "https://sns.us-east-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-east-1:123456789012:MyTopic:abcdefgh-ijkl-mnop-qrst-uvwxyzabcdef"
}`
var notificationPayload sns.Payload
// 将JSON字符串解析到sns.Payload结构体中
err := json.Unmarshal([]byte(notificationJson), ¬ificationPayload)
if err != nil {
log.Fatalf("Error unmarshalling JSON: %v", err)
}
// 调用VerifyPayload()方法执行签名验证
verifyErr := notificationPayload.VerifyPayload()
if verifyErr != nil {
log.Fatalf("Payload signature verification failed: %v", verifyErr)
}
fmt.Println("Payload signature is valid!")
fmt.Printf("Message: %s\n", notificationPayload.Message)以上就是Go语言中AWS SNS消息签名验证实践指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号