Coinbase API Powershell 签名无效

Coinbase API invalid signature with Powershell

我想使用 Powershell 通过 Coinbase API 检索账户余额。

我从 c​​oinbase api 文档中编写了以下代码,但最后一个请求引发了以下错误:

Invoke-RestMethod : {"errors":[{"id":"authentication_error","message":"invalid signature"}]}

这是我的代码。 怎么了?谢谢。

$accounts = 'https://api.coinbase.com/v2/accounts'
$time = 'https://api.coinbase.com/v2/time'
$epochtime = [string]((Invoke-WebRequest $time | ConvertFrom-Json).data).epoch

$method = 'GET'
$requestpath = '/v2/accounts'
$secret_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

$sign = $epochtime + $method + $requestpath
$hmacsha = New-Object System.Security.Cryptography.HMACSHA256
$hmacsha.key = [Convert]::FromBase64String($secret_key)
$signature = $hmacsha.ComputeHash([Text.Encoding]::ASCII.GetBytes($sign))
$signature = [Convert]::ToBase64String($signature)

$header = @{
"CB-ACCESS-SIGN"=$signature
"CB-ACCESS-TIMESTAMP"=$epochtime
"CB-VERSION" = '2017-08-07'
"CB-ACCESS-KEY"='xxxxxxxxxxxxxx'
}

Invoke-WebRequest $accounts -Headers $header

希望这能让你继续前进。我今天刚开始研究一个模块,却卡在了同样的事情上。我在尝试自己解决问题时遇到了您的问题。我想我会分享我的发现。祝你好运!

$accounts = 'https://api.coinbase.com/v2/accounts'
$time = 'https://api.coinbase.com/v2/time'
$epochtime = [string]((Invoke-WebRequest $time | ConvertFrom-Json).data).epoch

$method = 'GET'
$requestpath = '/v2/accounts'
$secret_key = (Get-CoinBaseAPIKeys).Secret

$sign = $epochtime + $method + $requestpath
$hmacsha = New-Object System.Security.Cryptography.HMACSHA256
$hmacsha.key = [Text.Encoding]::UTF8.GetBytes($secret_key)
$computeSha = $hmacsha.ComputeHash([Text.Encoding]::UTF8.GetBytes($sign))

漫漫长路,供参考:

$signature = ""
foreach ( $c in $computeSha )
{
    $signature += "{0:x2}" -f $c 
}

捷径。奇怪的是我被困在同一个问题上,因为捷径 生成 UPPER CASE HEX 并且长途 ^^above^^ 转换为小写 HEX。 CoinBase API 将只接受小写的 HEX 签名。

$signature = ([System.BitConverter]::ToString($computeSha) -replace "-").ToLower()

现在我们已经弄清楚了签名,剩下的应该会很好。我删除了 CB_VERSION 因为它将默认为您自己的 API 版本。我的默认值不同,所以我只是删除了它。

$header = @{
"CB-ACCESS-SIGN"=$signature
"CB-ACCESS-TIMESTAMP"=$epochtime
"CB-ACCESS-KEY"=(Get-CoinBaseAPIKeys).Key
}

$result = Invoke-WebRequest $accounts -Headers $header -Method Get -ContentType "application/json"
$accounts = $result.Content | ConvertFrom-Json
Write-Output $accounts.data

关于存储 PRIVATE KEY/SECRET 的旁白,您可以在这里找到一些想法: https://github.com/cmaahs/BittrexAPI/tree/master/Encryption。随意抓住它并根据需要进行修改。最好将您的 KEY/SECRET 加密存储在注册表中,而不是作为脚本中的纯文本或作为环境变量。