Help : Signing a request for an API call

API reference : API Document - Trying to achieve 7.1.4 Sign a request with a body

Topic: 7.1.4 Sign a request with a body

So from this reference document i am trying to sign the below.

{\n
“surname”: “Kierkegaard”,\n
“givenName”: “Søren”,\n
“userGroup”: “Guests in suite 102”\n
}

The body in this example contains 88 printable characters and 4 line feed characters, resulting in 92 Unicode
characters. (Note that there are 2 space characters at the beginning of each indented line and that the line breaks in
this example are single line feed characters. Unlike the HTTP header, which always uses both carriage return and
line feed in the line breaks, the line breaks of the body can be of any type.)

When the body is encoded as UTF-8, ø (U+00F8) is encoded as 0xc3 0xb8 so the 92 characters will occupy 93
octets. The MD5 digest of these octets is 943120b729dd663786412ac352cebd13. Encoded as Base64 it becomes
lDEgtyndZjeGQSrDUs69Ew==.

$body = @"
{
  "surname": "Kierkegaard",
  "givenName": "Søren",
  "userGroup": "Guests in suite 102"
}
"@

$bodyBytes = [Text.Encoding]::UTF8.GetBytes($body)
$md5 = New-Object Security.Cryptography.MD5CryptoServiceProvider
$bodyHashBytes = $md5.ComputeHash($bodyBytes)
$contentMD5Base64 = [Convert]::ToBase64String($bodyHashBytes)

But i dont seem to get lDEgtyndZjeGQSrDUs69Ew== no matter what formatting i try with the body.

Any help will be awesome.

Thank you,
Vikash

This is a bit convoluted, but the only way I’ve found to get the expected hash is to convert it to and from JSON. The JSON that ConvertTo-Json outputs implements new lines as \r\n even when VSCode is configured to LF only. So the \r needs to be replaced:

$body = @"
{
  "surname": "Kierkegaard",
  "givenName": "Søren",
  "userGroup": "Guests in suite 102"
}
"@

$jsonBody = ($body | ConvertTo-Json) -replace "\\r"
$bodyFromJson = $jsonBody | ConvertFrom-Json

$bodyBytes = [Text.Encoding]::UTF8.GetBytes($bodyFromJson)
$md5 = New-Object Security.Cryptography.MD5CryptoServiceProvider
$bodyHashBytes = $md5.ComputeHash($bodyBytes)
$contentMD5Base64 = [Convert]::ToBase64String($bodyHashBytes)

Thank you Matt.
Cheers!