将python请求转换为Powershell invoke-restmethod

时间:2020-05-04 21:13:26

标签: python powershell

我用Python获得了这段脚本,我想将其转换为PowerShell:

method = "GET"
URL = "PeRT RESTful API URL"
contentType = ""
publicAccessKey = "Your Public Access Key"
date = datetime.now().strftime("%a, %d %b %Y %X +0000")
cotentMd5 = ""
secretAccessKey = "Your Secret Access Key"

# URL used to create signature should not include parameters!!!
stringToSign = method + "\n" + url + "\n" + contentType + "\n" + publicAccessKey + "\n" + date + "\n" + cotentMd5
#print(stringToSign)
message = bytes(stringToSign).encode('utf-8')
secret = bytes(secretAccessKey).encode('utf-8')
signature = base64.b64encode(hmac.new(secret, message, digestmod=hashlib.sha256).digest())

headers = {
    "Authorization": publicAccessKey + ":" + signature,
    "Date" : date
}

response = requests.get(url, headers=headers)

这是我写的:

$URL = "PeRT RESTful API URL"
$hmacsha = New-Object System.Security.Cryptography.HMACSHA256
publicAccessKey = "Your Public Access Key"
secretAccessKey = "Your Secret Access Key"
$date= Get-Date -Format "ddd, dd MMM yyyy HH:mm:ss +0000"
$stringToSign= "GET" + "`n" + $baseURL + "`n" + "" + "`n" + $publicAccessKey + "`n" + $date + "`n" + ""

$hmacsha.key= [System.Text.Encoding]::ASCII.GetBytes($secretAccessKey)
$signature = $hmacsha.ComputeHash([Text.Encoding]::ASCII.GetBytes($stringToSign))
$signature = [Convert]::ToBase64String($signature)

$headers = @{ "Authorization" = $publicAccessKey + ":" + $signature ; "Date" = $date }

$response = Invoke-RestMethod -Uri $URL -Headers $headers

获取“ HTTP状态401-无效的客户端ID或密码。”

有人可以发现问题吗?

1 个答案:

答案 0 :(得分:1)

python使用UTF-8,而powershell使用ASCII

在您的代码中尝试使用[system.Text.Encoding]::UTF8代替[System.Text.Encoding]::ASCII

相关问题