PowerShell JWT PrivateKey x509Сертификаты - PullRequest
0 голосов
/ 15 мая 2018

Я работаю над проектом по созданию соединителя JWT с Box, который несколько команд могут использовать для своих собственных приложений.

У меня проблема с Закрытым ключом и при создании подписи. У меня нет четкого понимания сертификатов и что делать здесь. Может ли кто-нибудь объяснить, что я делаю неправильно и что мне нужно делать?

Вот код, который я пишу:

class BoxJWT
{
    [string]$url;
    [string]$clientID;
    [string]$clientSecret;
    [string]$enterpriseID;    
    [string]$publicKeyID;    
    [string]$privateKeyID;
    [string]$passphrase;

    <# ========&&==========&&==========&&==========&&======== #>
    <# ========&&========= Connect to Box =========&&======== #>
    <# ========&&==========&&==========&&==========&&======== #>
    [object]BoxConnect()
    {
        #Get the bytes of the PrivateKey
        $prik = [System.Text.Encoding]::UTF8.GetBytes($this.privateKeyID)
        $exp = [int][double]::parse((Get-Date -Date $((Get-Date).AddSeconds(60).ToUniversalTime()) -UFormat %s)) 

        #Create the header
        $headers = @{
           "alg" = "RS256"; 
           "typ" = "JWT"; 
        } | ConvertTo-Json -Compress

        #Create the claim
        $claim = @{
           "iss" = $this.clientID;
           "sub" = $this.enterpriseID; 
           "box_sub_type" = "enterprise";
           "aud" = 'https://api.box.com/oauth2/token';
           "exp" = $exp;
           "jti" = (1..20 | %{ '{0:X}' -f (Get-Random -Max 128) }) -join ''
        } | ConvertTo-Json -Compress

        $headers_base64 = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($headers)).Split('=')[0].Replace('+', '-').Replace('/', '_') 
        $claim_base64 = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($claim)).Split('=')[0].Replace('+', '-').Replace('/', '_') 

       #Prepare the signature.
       $pre_signature = ($headers_base64 + "." + $claim_base64)

       $encyption = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate2
       $encyption.Import($prik)

       #$JWTAssertion = "$headers_base64.$claim_base64.$signature" 

       #$body = 'grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&client_id=' + $this.clientID + '&client_secret=' + $this.clientSecret + '&assertion='+ $JWTAssertion
       #Invoke-RestMethod -Uri $this.url -Body $body -Method Post -ContentType "application/x-www-form-urlencoded"

       return '';
 }
}

$file = "$env:userprofile\Desktop\box_config.json"
$cont = Get-Content $file | ConvertFrom-Json
$v = New-Object -TypeName BoxJWT
$v.url = "https://api.box.com/oauth2/token";
$v.clientID = $cont.boxAppSettings.clientID
$v.clientSecret = $cont.boxAppSettings.clientSecret
$v.enterpriseID = $cont.enterpriseID
$v.passphrase = $cont.boxAppSettings.appAuth.passphrase
$v.privateKeyID = $cont.boxAppSettings.appAuth.privateKey
$v.publicKeyID = $cont.boxAppSettings.appAuth.publicKeyID

$v.BoxConnect()

Ошибка:

Exception calling "Import" with "1" argument(s): "Cannot find the requested 
object.
"
At C:\Users\username\Box\username\object-jwt.ps1:44 char:9
+         $encyption.Import($prik)
+         ~~~~~~~~~~~~~~~~~~~~~~~~   
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : CryptographicException

Любая помощь очень ценится.

Спасибо!

1 Ответ

0 голосов
/ 16 мая 2018

Хорошо, так что после дальнейшего погружения в это мне было проще использовать SDK и назвать его VIA PowerShell

$dlls = Get-ChildItem '.\Lib'

foreach($dll in $dlls)
{
    $library = get-childitem $dll.FullName -Recurse | Where-Object {$_ -like "*.dll"}
   if($library)
   {
       Add-type -Path $library.FullName
   }
}

$file = "$env:USERPROFILE\Desktop\box_config.json"
$json = Get-Content $file

$iBoxConfig = [Box.V2.Config.BoxConfig]::CreateFromJsonString($json)
$JWTAuth = [Box.V2.JWTAuth.BoxJWTAuth]::new($iBoxConfig)

$adminToken = $JWTAuth.AdminToken()
$client = $JWTAuth.AdminClient($adminToken)

Вот расположение Box SDK: https://github.com/box/box-windows-sdk-v2

Я надеюсь, что это помогает другим.Следующие библиотеки были необходимы для этого, и мне пришлось загружать их в порядке, указанном ниже:

Microsoft.IdentityModel.6.1.7600.16394
Microsoft.IdentityModel.Extensions.1.0.0
Microsoft.IdentityModel.Logging.1.1.4
Microsoft.IdentityModel.Tokens.5.1.4
Microsoft.NETCore.Platforms.1.1.0
Microsoft.Win32.Primitives.4.3.0
NETStandard.Library.1.6.1
Newtonsoft.Json.10.0.3
Newtonsoft.Json.9.0.0
Portable.BouncyCastle.1.8.1.2
System.AppContext.4.3.0
System.Collections.4.3.0
System.Collections.Concurrent.4.3.0
System.Console.4.3.0
System.Diagnostics.Debug.4.3.0
System.Diagnostics.DiagnosticSource.4.0.0
System.Diagnostics.DiagnosticSource.4.3.0
System.Diagnostics.Tools.4.3.0
System.Diagnostics.Tracing.4.3.0
System.Globalization.4.3.0
System.Globalization.Calendars.4.3.0
System.IdentityModel.Tokens.Jwt.5.1.4
System.IO.4.3.0
System.IO.Compression.4.3.0
System.IO.Compression.ZipFile.4.3.0
System.IO.FileSystem.4.3.0
System.IO.FileSystem.Primitives.4.3.0
System.Linq.4.3.0
System.Linq.Expressions.4.3.0
System.Net.Http.4.3.0
System.Net.Primitives.4.3.0
System.Net.Sockets.4.3.0
System.ObjectModel.4.3.0
System.Reflection.4.3.0
System.Reflection.Extensions.4.3.0
System.Reflection.Primitives.4.3.0
System.Resources.ResourceManager.4.3.0
System.Runtime.4.3.0
System.Runtime.Extensions.4.3.0
System.Runtime.Handles.4.3.0
System.Runtime.InteropServices.4.3.0
System.Runtime.InteropServices.RuntimeInformation.4.3.0
System.Runtime.Numerics.4.3.0
System.Security.Cryptography.Algorithms.4.3.0
System.Security.Cryptography.Encoding.4.3.0
System.Security.Cryptography.Primitives.4.3.0
System.Security.Cryptography.X509Certificates.4.3.0
System.Text.Encoding.4.3.0
System.Text.Encoding.Extensions.4.3.0
System.Text.RegularExpressions.4.3.0
System.Threading.4.3.0
System.Threading.Tasks.4.3.0
System.Threading.Timer.4.3.0
System.Xml.ReaderWriter.4.3.0
System.Xml.XDocument.4.3.0
z_BouncyCastle.1.8.1
z_Box.V2.3.3.0
z_Box.V2.Core.3.3.0
z_Microsoft.Identity.Model.Extensions.2.0.1459.0
...