Skip to content

Instantly share code, notes, and snippets.

@CosmosKey
Created October 12, 2024 16:42
Show Gist options
  • Save CosmosKey/56dd22155a651749aeb9b03f93c5ba9d to your computer and use it in GitHub Desktop.
Save CosmosKey/56dd22155a651749aeb9b03f93c5ba9d to your computer and use it in GitHub Desktop.
param(
$cert = $(Get--ChildItem Cert:\LocalMachine\My\1231231231231231231231231231231231231231),
$baseUrl = "https://<adfs.server>/adfs/services/trust"
)
function Get-Base64UrlDecode {
param([string[]]$InputString,[switch]$AsByteArray)
process {
$InputString | ForEach-Object {
$s = $_.Replace('-', '+').Replace('_', '/')
if($s.Length%4 -eq 2){$s = "$s=="}
if($s.Length%4 -eq 3){$s = "$s="}
if($AsByteArray) {
[convert]::FromBase64String($s)
} else {
[text.encoding]::Utf8.GetString([convert]::FromBase64String($s) )
}
}
}
}
$jwt = Get-JwtToken -Certificate $cert
$oidcConfigUrl = "$baseUrl/.well-known/openid-configuration"
$jwks = Invoke-RestMethod (Invoke-RestMethod $oidcConfigUrl).jwks_uri
$headerB64,$claimsB64,$signB64 = $jwt.Split(".")
$header = Get-Base64UrlDecode $headerB64 | ConvertFrom-Json
$claims = Get-Base64UrlDecode $claimsB64 | ConvertFrom-Json
$key = $jwks.Keys | Where-Object Kid -eq $header.kid
$signingCert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new([convert]::FromBase64String($key.x5c))
$modulus = Get-Base64UrlDecode $key.n -AsByteArray
$exponent = Get-Base64UrlDecode $key.e -AsByteArray
$rsaParams = New-Object System.Security.Cryptography.RSAParameters
$rsaParams.Modulus = $modulusBytes
$rsaParams.Exponent = $exponentBytes
$rsa = [System.Security.Cryptography.RSA]::Create()
$rsa.ImportParameters($rsaParams)
$headerAndClaims = "$headerB64.$claimsB64"
$dataBytes = [System.Text.Encoding]::ASCII.GetBytes($headerAndClaims)
$signatureBytes = Get-Base64UrlDecode $signB64 -AsByteArray
$hashAlgorithm = [System.Security.Cryptography.HashAlgorithmName]::SHA256
$valid = $rsa.VerifyData($dataBytes, $signatureBytes, $hashAlgorithm, [System.Security.Cryptography.RSASignaturePadding]::Pkcs1)
$valid
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment