Imports System.Security.Cryptography
Imports System.Text
Imports Microsoft.IdentityModel.Tokens
Imports Newtonsoft.Json

Public Class CryptoHelper

    Public Shared Function GetPagoHash(input As String) As String
        Using sha256 As SHA256 = SHA256.Create()
            Dim hash As Byte() = sha256.ComputeHash(Encoding.UTF8.GetBytes(input))
            Dim sha256Base64 As String = Convert.ToBase64String(hash)
            Return sha256Base64
        End Using
    End Function

#Region "SECURITY_HASH_V3"

    Public Shared Function GenerateJWKSignature(kid As String, kBase64Url As String, bodyJson As String) As String
        ' JWS header
        Dim headerObj = New With {
            .alg = "HS512",
            .typ = "JWT",
            .kid = kid
        }
        Dim headerJson As String = JsonConvert.SerializeObject(headerObj)
        Dim headerB64 As String = Base64UrlEncoder.Encode(headerJson)

        Dim payloadB64 As String = Base64UrlEncoder.Encode(bodyJson)

        Dim signingInput As String = $"{headerB64}.{payloadB64}"

        Dim keyBytes As Byte() = Base64UrlEncoder.DecodeBytes(kBase64Url)

        Dim signatureBytes As Byte()
        Using hmac As New HMACSHA512(keyBytes)
            signatureBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(signingInput))
        End Using

        Dim signatureB64 As String = Base64UrlEncoder.Encode(signatureBytes)
        Return $"{headerB64}.{payloadB64}.{signatureB64}"
    End Function
#End Region

End Class
