Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
Go语言中AWS SNS消息签名验证实践指南_创想鸟

Go语言中AWS SNS消息签名验证实践指南

Go语言中AWS SNS消息签名验证实践指南

本教程详细阐述了在go语言中安全验证aws sns消息签名的过程。我们将探讨签名验证的核心原理,包括规范化字符串、哈希生成与断言,并指出手动实现中常见的挑战。最终,推荐并演示如何利用现有的go.sns库高效、可靠地完成签名验证,确保消息的真实性和完整性。

引言:AWS SNS消息签名的重要性

AWS Simple Notification Service (SNS) 是一种高度可用的、灵活的、完全托管的发布/订阅消息服务。当SNS将消息发送到HTTP/S端点时,为了确保消息的真实性和完整性,AWS会对消息进行数字签名。作为消息接收方,对这些签名进行验证至关重要,它可以防止未经授权的第三方篡改消息内容或伪造消息来源,从而保障应用程序的安全性。

AWS SNS签名验证原理概述

AWS SNS的签名验证过程遵循标准的数字签名机制,涉及以下几个核心步骤:

构建规范化字符串 (Canonical String)接收到的SNS消息是一个JSON对象。在进行签名之前,AWS会根据消息中的特定字段(Message、MessageId、Subject、Timestamp、TopicArn、Type等)以特定顺序和格式构建一个“规范化字符串”。这个字符串是签名计算的原始输入。

例如,一个规范化字符串的结构可能如下所示:

MessageHello from SNS!MessageIda1b2c3d4-e5f6-7890-1234-567890abcdefSubjectMy SubjectTimestamp2023-10-27T12:00:00.000ZTopicArnarn:aws:sns:us-east-1:123456789012:MyTopicTypeNotification

请注意,如果Subject字段不存在,则在规范化字符串中不应包含Subject及其值。

立即学习“go语言免费学习笔记(深入)”;

生成派生哈希值 (Derived Hash Value)这是指接收方对本地构建的规范化字符串进行哈希运算。AWS SNS通常使用SHA1或SHA256哈希算法,具体取决于消息中的SignatureVersion字段(版本1通常使用SHA1)。这个哈希值代表了消息内容的“指纹”。

生成断言哈希值 (Asserted Hash Value)SNS消息中包含一个Signature字段,这是一个Base64编码的字符串,它是AWS使用其私钥对规范化字符串的哈希值进行加密(签名)后的结果。断言哈希值是通过以下步骤获得的:

从SigningCertURL字段指定的URL下载AWS的X.509签名证书。从证书中提取AWS的公钥。使用该公钥对消息中的Base64解码后的Signature进行解密(或更准确地说是验证签名操作)。解密后的结果即为断言哈希值。

验证过程将步骤2中生成的派生哈希值与步骤3中生成的断言哈希值进行比较。如果两者完全一致,则表明消息未被篡改,且确实由AWS SNS发送。

Go语言手动实现签名验证的挑战与解析

在Go语言中手动实现SNS签名验证,需要处理网络请求、证书解析、哈希计算和RSA签名验证等多个环节。以下是具体步骤及常见问题解析:

构建规范化字符串根据上述原理,需要根据SNS消息结构动态构建字符串。

package mainimport (    "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("Messagen")    sb.WriteString(n.Message)    sb.WriteString("nMessageIdn")    sb.WriteString(n.MessageId)    if n.Subject != "" {        sb.WriteString("nSubjectn")        sb.WriteString(n.Subject)    }    sb.WriteString("nTimestampn")    sb.WriteString(n.Timestamp)    sb.WriteString("nTopicArnn")    sb.WriteString(n.TopicArn)    sb.WriteString("nTypen")    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}

推荐方案:使用go.sns库简化验证流程

鉴于手动实现SNS签名验证涉及的复杂性和潜在错误,强烈建议使用经过社区验证的第三方库。github.com/robbiet480/go.sns库就是这样一个优秀的选择,它封装了所有必要的逻辑,大大简化了验证过程。

安装go.sns库

go get github.com/robbiet480/go.sns

使用示例

该库提供了一个简洁的API来处理SNS消息的JSON解析和签名验证。

package mainimport (    "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), &notificationPayload)    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: %sn", notificationPayload.Message)

以上就是Go语言中AWS SNS消息签名验证实践指南的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1421921.html

赞 (0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
Go语言:程序化调用gorilla/mux处理器并处理路由变量
上一篇 2025年12月16日 16:24:33
聚焦Go语言惯用法:优化文件日期提取函数
下一篇 2025年12月16日 16:24:37

相关推荐

发表回复

登录后才能评论
关注微信