AWS API - 不接受我的签名

时间:2011-04-08 12:08:20

标签: vb.net amazon-ec2 amazon-web-services load-balancing

我在这里尝试过所有内容,但亚马逊负载均衡器API不接受我的签名。

无论我尝试什么,我都会收到“403 SignatureDoesNotMatch”回复。我可能错过了一些明显的东西,但花了几个小时试图找出那是什么,我就在我的系绳的尽头。请帮忙!!感谢。

这是我的代码:

Public Sub DeregisterInstanceFromLoadBalance(ByVal strServerID As String)
    Dim strURL As String
    strURL = "http://elasticloadbalancing.amazonaws.com/?"
    Dim strTimestamp As String = PercentEncodeRfc3986(DateTime.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'"))

    Dim strParams As String
    strParams = "AWSAccessKeyId=<MY_API_KEY>" & _
    "&Action=DeregisterInstancesFromLoadBalancer" & _
    "&Instances.member.N=" & strServerID & _
    "&LoadBalancerName=ATTB" & _
    "&SignatureMethod=HmacSHA256" & _
    "&SignatureVersion=2" & _
    "&Timestamp=" & strTimestamp & _
    "&Version=2009-05-15"

    Dim strStringToSign As String = "GET\nelasticloadbalancing.amazonaws.com\n/\n" & strParams

    strURL = strURL & strParams & "&Signature=" & PercentEncodeRfc3986(HashString(strStringToSign))

    Dim wc As New WebClient()
    Dim strResponse As String
    strResponse = wc.DownloadString(strURL)

End Sub


Private Const PRIVATE_KEY As String = "<MY_PRIVATE_KEY>"

Private Function HashString(ByVal StringToHash As String) As String
    Dim Key() As Byte = Encoding.UTF8.GetBytes(PRIVATE_KEY)
    Dim XML() As Byte = Encoding.UTF8.GetBytes(StringToHash)
    Dim myHMACSHA256 As New System.Security.Cryptography.HMACSHA256(Key)
    Dim HashCode As Byte() = myHMACSHA256.ComputeHash(XML)
    Return Convert.ToBase64String(HashCode)
End Function


Private Function PercentEncodeRfc3986(ByVal str As String) As String

    str = HttpUtility.UrlEncode(str, System.Text.Encoding.UTF8)
    str = str.Replace("'", "%27").Replace("(", "%28").Replace(")", "%29").Replace("*", "%2A").Replace("!", "%21").Replace("%7e", "~").Replace("+", "%20").Replace("%7E", "~")

    Dim sbuilder As StringBuilder = New StringBuilder(str)
    For i As Int32 = 0 To sbuilder.Length - 1

        If sbuilder(i) = "%" Then
            If (Char.IsLetter(sbuilder(i + 1)) OrElse Char.IsLetter(sbuilder(i + 2))) Then
                sbuilder(i + 1) = Char.ToUpper(sbuilder(i + 1))
                sbuilder(i + 2) = Char.ToUpper(sbuilder(i + 2))
            End If
        End If
    Next
    Return sbuilder.ToString()
End Function

1 个答案:

答案 0 :(得分:1)

好的,我深究了这一点。有一些问题;亚马逊的文档。

  • 在VB.Net中,我应该使用 ControlChars.Lf 而不是“\ n”
  • 记录的 Instances.member.N 参数 是错的,应该是
    Instances.member。[N] .InstanceId ,其中[N]是实例索引,
    1 开始。这回来了 相当混乱的错误信息
    “LoadBalancerNotFound”。
  • 正确的域名 elasticloadbalancing。[availability_zone] .amazonaws.com ;文档中使用的示例也没有特别清楚。 (尽管域名使用记录在其他地方)