PowerShell Function - Create Signature for writing Log Analytics data

When writing data to Log Analytics, data needs to be signed.

In a previous post (PowerShell Function - Write Data to Log Analytics | Laurie Rhodes' Info ) I showed how submit data to a workspace using Powershell and APIs.  This function is used to get the signature for the data being posted.

<#
  Function:  Get-Signature

  Purpose:  To retrieve a current Analytics Workspace Key for a given workspace

  Parameters:   -WorkspaceId      = Log Analytics Workspace GUID
                -sharedKey        = Log Analytics shared key (either primary or secondary)
                -date             = (optional) date override 
                -contentLength    = The length (in characters) of the payload / body of JSON being submitted.
                -method           = The API Method used with the request (POST for Analytics)
                -contentType      = The content type of the request - "application/json"
                -resource         = "/api/logs" for Log Analytics workspaces

  Example:  
    
        $signature = Get-Signature `
                            -WorkspaceId $WorkspaceId `
                            -sharedKey $sharedKey `
                            -date [DateTime]::UtcNow.ToString("r") rfc1123 `
                            -contentLength $body.Length `
                            -method "POST" `
                            -contentType "application/json"  `
                            -resource "/api/logs"


#>
Function Get-Signature (){
    param (
        [Parameter(Mandatory = $true)] [string] $WorkspaceId ,
        [Parameter(Mandatory = $true)] [string] $sharedKey ,
        [Parameter(Mandatory = $true)] [string] $date ,
        [Parameter(Mandatory = $true)] [string] $contentLength,
        [Parameter(Mandatory = $true)] [string] $method ,
        [Parameter(Mandatory = $true)] [string] $contentType ,
        [Parameter(Mandatory = $true)] [string] $resource
    )

    $xHeaders = "x-ms-date:" + $date
    $stringToHash = $method + "`n" + $contentLength + "`n" + $contentType + "`n" + $xHeaders + "`n" + $resource

    $bytesToHash = [Text.Encoding]::UTF8.GetBytes($stringToHash)
    $keyBytes = [Convert]::FromBase64String($sharedKey)

    $sha256 = New-Object System.Security.Cryptography.HMACSHA256
    $sha256.Key = $keyBytes
    $calculatedHash = $sha256.ComputeHash($bytesToHash)
    $encodedHash = [Convert]::ToBase64String($calculatedHash)
    $authorization = 'SharedKey {0}:{1}' -f $WorkspaceId,$encodedHash
    return $authorization
}

Tags