Skip to content

Instantly share code, notes, and snippets.

Created March 16, 2018 16:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/1c7cd4b1a0f8b2279e1f507586685a7b to your computer and use it in GitHub Desktop.
Save anonymous/1c7cd4b1a0f8b2279e1f507586685a7b to your computer and use it in GitHub Desktop.
function New-JWT (
[Parameter(Mandatory = $True)]
[ValidateSet("HS256", "HS384", "HS512")]
$Algorithm = "HS256",
$type = "JWT",
[Parameter(Mandatory = $True)]
[string]$Issuer = $null,
[int]$ValidforMinutes = 10,
[string]$Name = $null,
[Parameter(Mandatory = $True)]
$PrivateKey = $null
) {
$exp = [int][double]::parse((Get-Date -Date $((Get-Date).addminutes($ValidforMinutes).ToUniversalTime()) -UFormat %s))
[hashtable]$header = @{alg = $Algorithm; typ = $type}
[hashtable]$payload = @{iss = $Issuer; exp = $exp}
$headerjson = $header | ConvertTo-Json -Compress
$payloadjson = $payload | ConvertTo-Json -Compress
$headerjsonbase64 = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($headerjson)).Split('=')[0].Replace('+', '-').Replace('/', '_')
$payloadjsonbase64 = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($payloadjson)).Split('=')[0].Replace('+', '-').Replace('/', '_')
$ToBeSigned = $headerjsonbase64 + "." + $payloadjsonbase64
$SigningAlgorithm = switch ($Algorithm) {
"HS256" {New-Object System.Security.Cryptography.HMACSHA256}
"HS384" {New-Object System.Security.Cryptography.HMACSHA384}
"HS512" {New-Object System.Security.Cryptography.HMACSHA512}
}
$SigningAlgorithm.Key = [System.Text.Encoding]::UTF8.GetBytes($PrivateKey)
$Signature = [Convert]::ToBase64String($SigningAlgorithm.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($ToBeSigned))).Split('=')[0].Replace('+', '-').Replace('/', '_')
$JWT = "$headerjsonbase64.$payloadjsonbase64.$Signature"
$JWT
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment