From dd15fef9272a1104da6e50fdbb3b3086e6b53b6a Mon Sep 17 00:00:00 2001 From: William Cheng Date: Fri, 31 Jul 2020 16:55:23 +0800 Subject: [PATCH 1/2] better code format in powershell code --- .../powershell/Org.OpenAPITools.psm1.mustache | 2 +- .../about_Org.OpenAPITools.help.txt.mustache | 2 +- .../powershell/configuration.mustache | 14 +-- .../powershell/http_signature_auth.mustache | 114 +++++++----------- .../powershell/rsa_provider.mustache | 6 +- .../src/PSPetstore/Client/PSConfiguration.ps1 | 14 +-- .../powershell/src/PSPetstore/PSPetstore.psm1 | 2 +- .../Private/PSHttpSignatureAuth.ps1 | 114 +++++++----------- .../Private/PSRSAEncryptionProvider.cs | 6 +- .../en-US/about_PSPetstore.help.txt | 2 +- 10 files changed, 116 insertions(+), 160 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/powershell/Org.OpenAPITools.psm1.mustache b/modules/openapi-generator/src/main/resources/powershell/Org.OpenAPITools.psm1.mustache index ce575233bb86..7714f348b49f 100644 --- a/modules/openapi-generator/src/main/resources/powershell/Org.OpenAPITools.psm1.mustache +++ b/modules/openapi-generator/src/main/resources/powershell/Org.OpenAPITools.psm1.mustache @@ -4,7 +4,7 @@ # set $ErrorActionPreference to 'Stop' globally $ErrorActionPreference = 'Stop' -# store the API client's configuration +# store the API client's configuration $Script:Configuration = [System.Collections.HashTable]@{} $Script:CmdletBindingParameters = @('Verbose','Debug','ErrorAction','WarningAction','InformationAction','ErrorVariable','WarningVariable','InformationVariable','OutVariable','OutBuffer','PipelineVariable') diff --git a/modules/openapi-generator/src/main/resources/powershell/about_Org.OpenAPITools.help.txt.mustache b/modules/openapi-generator/src/main/resources/powershell/about_Org.OpenAPITools.help.txt.mustache index 10b226f136e9..a6a43671ace8 100644 --- a/modules/openapi-generator/src/main/resources/powershell/about_Org.OpenAPITools.help.txt.mustache +++ b/modules/openapi-generator/src/main/resources/powershell/about_Org.OpenAPITools.help.txt.mustache @@ -23,5 +23,5 @@ LONG DESCRIPTION Frameworks supported: - * PowerShell 3.0+ + * PowerShell {{{powershellVersion}}} or later * .NET 4.0 or later diff --git a/modules/openapi-generator/src/main/resources/powershell/configuration.mustache b/modules/openapi-generator/src/main/resources/powershell/configuration.mustache index 622bce2b65ae..499a39bf3eb2 100644 --- a/modules/openapi-generator/src/main/resources/powershell/configuration.mustache +++ b/modules/openapi-generator/src/main/resources/powershell/configuration.mustache @@ -388,7 +388,7 @@ a key. The 'Authorization' header is added to outbound HTTP requests. Ref: https://openapi-generator.tech .PARAMETER KeyId -KeyId for HTTP signing +KeyId for HTTP signing .PARAMETER KeyFilePath KeyFilePath for HTTP signing @@ -397,7 +397,7 @@ KeyFilePath for HTTP signing KeyPassPhrase, if the HTTP signing key is protected .PARAMETER HttpSigningHeader -HttpSigningHeader list of HTTP headers used to calculate the signature. The two special signature headers '(request-target)' and '(created)' +HttpSigningHeader list of HTTP headers used to calculate the signature. The two special signature headers '(request-target)' and '(created)' SHOULD be included. The '(created)' header expresses when the signature was created. The '(request-target)' header is a concatenation of the lowercased :method, an @@ -408,11 +408,11 @@ If no headers are specified then '(created)' sets as default. HashAlgrithm to calculate the hash, Supported values are "sha256" and "sha512" .PARAMETER SigningAlgorithm -SigningAlgorithm specifies the signature algorithm, supported values are "RSASSA-PKCS1-v1_5" and "RSASSA-PSS" +SigningAlgorithm specifies the signature algorithm, supported values are "RSASSA-PKCS1-v1_5" and "RSASSA-PSS" RSA key : Supported values "RSASSA-PKCS1-v1_5" and "RSASSA-PSS", for ECDSA key this parameter is not applicable .PARAMETER SignatureValidityPeriod -SignatureValidityPeriod specifies the signature maximum validity time in seconds. It accepts integer value +SignatureValidityPeriod specifies the signature maximum validity time in seconds. It accepts integer value .OUTPUTS @@ -459,11 +459,11 @@ function Set-{{{apiNamePrefix}}}ConfigurationHttpSigning { } } - if ($keyType -eq "RSA" -and + if ($keyType -eq "RSA" -and ($SigningAlgorithm -ne "RSASSA-PKCS1-v1_5" -and $SigningAlgorithm -ne "RSASSA-PSS" )) { throw "Provided Key and SigningAlgorithm : $SigningAlgorithm is not compatible." } - + if ($HttpSigningHeader -contains "(expires)" -and $SignatureValidityPeriod -le 0) { throw "SignatureValidityPeriod must be greater than 0 seconds." } @@ -486,7 +486,7 @@ function Set-{{{apiNamePrefix}}}ConfigurationHttpSigning { if ($null -ne $KeyPassPhrase) { $httpSignatureConfiguration["KeyPassPhrase"] = $KeyPassPhrase } - + $Script:Configuration["HttpSigning"] = New-Object -TypeName PSCustomObject -Property $httpSignatureConfiguration } } diff --git a/modules/openapi-generator/src/main/resources/powershell/http_signature_auth.mustache b/modules/openapi-generator/src/main/resources/powershell/http_signature_auth.mustache index 69ab0b43bb10..fe6a3dc8ec6f 100644 --- a/modules/openapi-generator/src/main/resources/powershell/http_signature_auth.mustache +++ b/modules/openapi-generator/src/main/resources/powershell/http_signature_auth.mustache @@ -3,9 +3,9 @@ .SYNOPSIS Gets the headers for HTTP signature. .DESCRIPTION - Gets the headers for the http sigature. + Gets the headers for the http sigature. .PARAMETER Method - HTTP method + HTTP method .PARAMETER UriBuilder UriBuilder for url and query parameter .PARAMETER Body @@ -44,49 +44,43 @@ function Get-{{{apiNamePrefix}}}HttpSignedHeader { $TargetHost = $UriBuilder.Host $httpSigningConfiguration = Get-{{{apiNamePrefix}}}ConfigurationHttpSigning $Digest = $null - + #get the body digest $bodyHash = Get-{{{apiNamePrefix}}}StringHash -String $Body -HashName $httpSigningConfiguration.HashAlgorithm if ($httpSigningConfiguration.HashAlgorithm -eq "SHA256") { $Digest = [String]::Format("SHA-256={0}", [Convert]::ToBase64String($bodyHash)) - } - elseif ($httpSigningConfiguration.HashAlgorithm -eq "SHA512") { + } elseif ($httpSigningConfiguration.HashAlgorithm -eq "SHA512") { $Digest = [String]::Format("SHA-512={0}", [Convert]::ToBase64String($bodyHash)) } - + $dateTime = Get-Date #get the date in UTC $currentDate = $dateTime.ToUniversalTime().ToString("r") foreach ($headerItem in $httpSigningConfiguration.HttpSigningHeader) { - - if ($headerItem -eq $HEADER_REQUEST_TARGET) { + + if ($headerItem -eq $HEADER_REQUEST_TARGET) { $requestTargetPath = [string]::Format("{0} {1}{2}", $Method.ToLower(), $UriBuilder.Path, $UriBuilder.Query) $HttpSignatureHeader.Add($HEADER_REQUEST_TARGET, $requestTargetPath) - } - elseif ($headerItem -eq $HEADER_CREATED) { + } elseif ($headerItem -eq $HEADER_CREATED) { $created = Get-{{{apiNamePrefix}}}UnixTime -Date $dateTime -TotalTime TotalSeconds $HttpSignatureHeader.Add($HEADER_CREATED, $created) - } - elseif ($headerItem -eq $HEADER_EXPIRES) { + } elseif ($headerItem -eq $HEADER_EXPIRES) { $expire = $dateTime.AddSeconds($httpSigningConfiguration.SignatureValidityPeriod) $expireEpocTime = Get-{{{apiNamePrefix}}}UnixTime -Date $expire -TotalTime TotalSeconds $HttpSignatureHeader.Add($HEADER_EXPIRES, $expireEpocTime) - } - elseif ($headerItem -eq $HEADER_HOST) { + } elseif ($headerItem -eq $HEADER_HOST) { $HttpSignedRequestHeader[$HEADER_HOST] = $TargetHost $HttpSignatureHeader.Add($HEADER_HOST.ToLower(), $TargetHost) - } - elseif ($headerItem -eq $HEADER_DATE) { + } elseif ($headerItem -eq $HEADER_DATE) { $HttpSignedRequestHeader[$HEADER_DATE] = $currentDate $HttpSignatureHeader.Add($HEADER_DATE.ToLower(), $currentDate) - } - elseif ($headerItem -eq $HEADER_DIGEST) { + } elseif ($headerItem -eq $HEADER_DIGEST) { $HttpSignedRequestHeader[$HEADER_DIGEST] = $Digest $HttpSignatureHeader.Add($HEADER_DIGEST.ToLower(), $Digest) - }elseif($RequestHeader.ContainsKey($headerItem)){ + } elseif($RequestHeader.ContainsKey($headerItem)) { $HttpSignatureHeader.Add($headerItem.ToLower(), $RequestHeader[$headerItem]) - }else{ + } else { throw "Cannot sign HTTP request. Request does not contain the $headerItem header." } } @@ -99,7 +93,7 @@ function Get-{{{apiNamePrefix}}}HttpSignedHeader { } #Concatinate headers value separated by new line $headerValuesString = $headerValuesList -join "`n" - + #Gets the hash of the headers value $signatureHashString = Get-{{{apiNamePrefix}}}StringHash -String $headerValuesString -HashName $httpSigningConfiguration.HashAlgorithm @@ -112,8 +106,7 @@ function Get-{{{apiNamePrefix}}}HttpSignedHeader { -HashAlgorithmName $httpSigningConfiguration.HashAlgorithm ` -KeyPassPhrase $httpSigningConfiguration.KeyPassPhrase ` -SigningAlgorithm $httpSigningConfiguration.SigningAlgorithm - } - elseif ($KeyType -eq "EC") { + } elseif ($KeyType -eq "EC") { $headerSignatureStr = Get-{{{apiNamePrefix}}}ECDSASignature -ECKeyFilePath $httpSigningConfiguration.KeyFilePath ` -DataToSign $signatureHashString ` -HashAlgorithmName $httpSigningConfiguration.HashAlgorithm ` @@ -134,10 +127,10 @@ function Get-{{{apiNamePrefix}}}HttpSignedHeader { if ($HttpSignatureHeader.ContainsKey($HEADER_EXPIRES)) { $authorizationHeaderValue += [string]::Format(",expires={0}", $HttpSignatureHeader[$HEADER_EXPIRES]) } - - $authorizationHeaderValue += [string]::Format(",headers=""{0}"",signature=""{1}""", + + $authorizationHeaderValue += [string]::Format(",headers=""{0}"",signature=""{1}""", $headersKeysString , $headerSignatureStr) - + $HttpSignedRequestHeader[$HEADER_AUTHORIZATION] = $authorizationHeaderValue return $HttpSignedRequestHeader } @@ -147,7 +140,7 @@ function Get-{{{apiNamePrefix}}}HttpSignedHeader { Gets the RSA signature .DESCRIPTION - Gets the RSA signature for the http signing + Gets the RSA signature for the http signing .PARAMETER PrivateKeyFilePath Specify the API key file path .PARAMETER DataToSign @@ -168,11 +161,10 @@ function Get-{{{apiNamePrefix}}}RSASignature { [securestring]$KeyPassPhrase ) try { - + if ($hashAlgorithmName -eq "sha256") { $hashAlgo = [System.Security.Cryptography.HashAlgorithmName]::SHA256 - } - elseif ($hashAlgorithmName -eq "sha512") { + } elseif ($hashAlgorithmName -eq "sha512") { $hashAlgo = [System.Security.Cryptography.HashAlgorithmName]::SHA512 } @@ -188,31 +180,26 @@ function Get-{{{apiNamePrefix}}}RSASignature { if ($SigningAlgorithm -eq "RSASSA-PSS") { $signedBytes = $rsa.SignHash($DataToSign, $hashAlgo, [System.Security.Cryptography.RSASignaturePadding]::Pss) - } - else { + } else { $signedBytes = $rsa.SignHash($DataToSign, $hashAlgo, [System.Security.Cryptography.RSASignaturePadding]::Pkcs1) } - } - else { + } else { $rsa_provider_path = Join-Path -Path $PSScriptRoot -ChildPath "{{{apiNamePrefix}}}RSAEncryptionProvider.cs" $rsa_provider_sourceCode = Get-Content -Path $rsa_provider_path -Raw - Add-Type -TypeDefinition $rsa_provider_sourceCode - + Add-Type -TypeDefinition $rsa_provider_sourceCode + [System.Security.Cryptography.RSA]$rsa = [RSAEncryption.RSAEncryptionProvider]::GetRSAProviderFromPemFile($PrivateKeyFilePath, $KeyPassPhrase) - + if ($SigningAlgorithm -eq "RSASSA-PSS") { throw "$SigningAlgorithm is not supported on $($PSVersionTable.PSVersion)" - } - else { + } else { $signedBytes = $rsa.SignHash($DataToSign, $hashAlgo, [System.Security.Cryptography.RSASignaturePadding]::Pkcs1) } - } $signedString = [Convert]::ToBase64String($signedBytes) return $signedString - } - catch { + } catch { throw $_ } } @@ -222,7 +209,7 @@ function Get-{{{apiNamePrefix}}}RSASignature { Gets the ECDSA signature .DESCRIPTION - Gets the ECDSA signature for the http signing + Gets the ECDSA signature for the http signing .PARAMETER PrivateKeyFilePath Specify the API key file path .PARAMETER DataToSign @@ -249,7 +236,7 @@ function Get-{{{apiNamePrefix}}}ECDSASignature { throw "key file path does not exist." } - if($PSVersionTable.PSVersion.Major -lt 7){ + if ($PSVersionTable.PSVersion.Major -lt 7) { throw "ECDSA key is not supported on $($PSVersionTable.PSVersion), Use PSVersion 7.0 and above" } @@ -263,27 +250,23 @@ function Get-{{{apiNamePrefix}}}ECDSASignature { #$ecdsa = [System.Security.Cryptography.ECDsaCng]::New($cngKey) $ecdsa = [System.Security.Cryptography.ECDsaCng]::New() [int]$bytCount =0 - if(![string]::IsNullOrEmpty($KeyPassPhrase)){ + if (![string]::IsNullOrEmpty($KeyPassPhrase)) { $ecdsa.ImportEncryptedPkcs8PrivateKey($KeyPassPhrase,$keyBytes,[ref]$bytCount) + } else { + $ecdsa.ImportPkcs8PrivateKey($keyBytes,[ref]$bytCount) } - else{ - $ecdsa.ImportPkcs8PrivateKey($keyBytes,[ref]$bytCount) - } - + if ($HashAlgorithmName -eq "sha512") { $ecdsa.HashAlgorithm = [System.Security.Cryptography.CngAlgorithm]::Sha512 - } - else { + } else { $ecdsa.HashAlgorithm = [System.Security.Cryptography.CngAlgorithm]::Sha256 } $signedBytes = $ecdsa.SignHash($DataToSign) $signedString = [System.Convert]::ToBase64String($signedBytes) return $signedString - } - <# .Synopsis Gets the hash of string. @@ -295,7 +278,7 @@ function Get-{{{apiNamePrefix}}}ECDSASignature { Specifies the hash name to calculate the hash, Accepted values are "SHA1", "SHA256" and "SHA512" It is recommneded not to use "SHA1" to calculate the Hash .Outputs -String + String #> Function Get-{{{apiNamePrefix}}}StringHash { param( @@ -305,9 +288,9 @@ Function Get-{{{apiNamePrefix}}}StringHash { [Parameter(Mandatory = $true)] [ValidateSet("SHA1", "SHA256", "SHA512")] $HashName - ) + ) $hashAlogrithm = [System.Security.Cryptography.HashAlgorithm]::Create($HashName) - $hashAlogrithm.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($String)) + $hashAlogrithm.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($String)) } <# @@ -359,7 +342,6 @@ function Get-{{{apiNamePrefix}}}CryptographicScheme { return $SigningAlgorithm } - <# .Synopsis Gets the key type from the pem file. @@ -390,20 +372,16 @@ function Get-{{{apiNamePrefix}}}KeyTypeFromFile { if ($key[0] -match $rsaPrivateKeyHeader -and $key[$key.Length - 1] -match $rsaPrivateFooter) { $KeyType = "RSA" - - } - elseif ($key[0] -match $ecPrivateKeyHeader -and $key[$key.Length - 1] -match $ecPrivateKeyFooter) { + } elseif ($key[0] -match $ecPrivateKeyHeader -and $key[$key.Length - 1] -match $ecPrivateKeyFooter) { $keyType = "EC" - } - elseif ($key[0] -match $ecPrivateKeyHeader -and $key[$key.Length - 1] -match $ecPrivateKeyFooter) { + } elseif ($key[0] -match $ecPrivateKeyHeader -and $key[$key.Length - 1] -match $ecPrivateKeyFooter) { <#this type of key can hold many type different types of private key, but here due lack of pem header - Considering this as EC key - #> + Considering this as EC key + #> #TODO :- update the key based on oid $keyType = "EC" - } - else { + } else { throw "Either the key is invalid or key is not supported" } - return $keyType -} \ No newline at end of file + return $keyType +} diff --git a/modules/openapi-generator/src/main/resources/powershell/rsa_provider.mustache b/modules/openapi-generator/src/main/resources/powershell/rsa_provider.mustache index 7a671929fb2b..451221fd8940 100644 --- a/modules/openapi-generator/src/main/resources/powershell/rsa_provider.mustache +++ b/modules/openapi-generator/src/main/resources/powershell/rsa_provider.mustache @@ -64,7 +64,7 @@ namespace RSAEncryption return binkey; } catch (System.FormatException) - { + { StringReader str = new StringReader(pvkstr); //-------- read PEM encryption info. lines and extract salt ----- @@ -234,7 +234,7 @@ namespace RSAEncryption { // ---- Now hash consecutively for count times ------ if (j == 0) - result = data00; //initialize + result = data00; //initialize else { Array.Copy(result, hashtarget, result.Length); @@ -276,4 +276,4 @@ namespace RSAEncryption return decryptedData; } } -} \ No newline at end of file +} diff --git a/samples/client/petstore/powershell/src/PSPetstore/Client/PSConfiguration.ps1 b/samples/client/petstore/powershell/src/PSPetstore/Client/PSConfiguration.ps1 index 8e6910f19707..0d115cc603c5 100644 --- a/samples/client/petstore/powershell/src/PSPetstore/Client/PSConfiguration.ps1 +++ b/samples/client/petstore/powershell/src/PSPetstore/Client/PSConfiguration.ps1 @@ -404,7 +404,7 @@ a key. The 'Authorization' header is added to outbound HTTP requests. Ref: https://openapi-generator.tech .PARAMETER KeyId -KeyId for HTTP signing +KeyId for HTTP signing .PARAMETER KeyFilePath KeyFilePath for HTTP signing @@ -413,7 +413,7 @@ KeyFilePath for HTTP signing KeyPassPhrase, if the HTTP signing key is protected .PARAMETER HttpSigningHeader -HttpSigningHeader list of HTTP headers used to calculate the signature. The two special signature headers '(request-target)' and '(created)' +HttpSigningHeader list of HTTP headers used to calculate the signature. The two special signature headers '(request-target)' and '(created)' SHOULD be included. The '(created)' header expresses when the signature was created. The '(request-target)' header is a concatenation of the lowercased :method, an @@ -424,11 +424,11 @@ If no headers are specified then '(created)' sets as default. HashAlgrithm to calculate the hash, Supported values are "sha256" and "sha512" .PARAMETER SigningAlgorithm -SigningAlgorithm specifies the signature algorithm, supported values are "RSASSA-PKCS1-v1_5" and "RSASSA-PSS" +SigningAlgorithm specifies the signature algorithm, supported values are "RSASSA-PKCS1-v1_5" and "RSASSA-PSS" RSA key : Supported values "RSASSA-PKCS1-v1_5" and "RSASSA-PSS", for ECDSA key this parameter is not applicable .PARAMETER SignatureValidityPeriod -SignatureValidityPeriod specifies the signature maximum validity time in seconds. It accepts integer value +SignatureValidityPeriod specifies the signature maximum validity time in seconds. It accepts integer value .OUTPUTS @@ -475,11 +475,11 @@ function Set-PSConfigurationHttpSigning { } } - if ($keyType -eq "RSA" -and + if ($keyType -eq "RSA" -and ($SigningAlgorithm -ne "RSASSA-PKCS1-v1_5" -and $SigningAlgorithm -ne "RSASSA-PSS" )) { throw "Provided Key and SigningAlgorithm : $SigningAlgorithm is not compatible." } - + if ($HttpSigningHeader -contains "(expires)" -and $SignatureValidityPeriod -le 0) { throw "SignatureValidityPeriod must be greater than 0 seconds." } @@ -502,7 +502,7 @@ function Set-PSConfigurationHttpSigning { if ($null -ne $KeyPassPhrase) { $httpSignatureConfiguration["KeyPassPhrase"] = $KeyPassPhrase } - + $Script:Configuration["HttpSigning"] = New-Object -TypeName PSCustomObject -Property $httpSignatureConfiguration } } diff --git a/samples/client/petstore/powershell/src/PSPetstore/PSPetstore.psm1 b/samples/client/petstore/powershell/src/PSPetstore/PSPetstore.psm1 index f0637343093c..9153f06cd47f 100644 --- a/samples/client/petstore/powershell/src/PSPetstore/PSPetstore.psm1 +++ b/samples/client/petstore/powershell/src/PSPetstore/PSPetstore.psm1 @@ -10,7 +10,7 @@ # set $ErrorActionPreference to 'Stop' globally $ErrorActionPreference = 'Stop' -# store the API client's configuration +# store the API client's configuration $Script:Configuration = [System.Collections.HashTable]@{} $Script:CmdletBindingParameters = @('Verbose','Debug','ErrorAction','WarningAction','InformationAction','ErrorVariable','WarningVariable','InformationVariable','OutVariable','OutBuffer','PipelineVariable') diff --git a/samples/client/petstore/powershell/src/PSPetstore/Private/PSHttpSignatureAuth.ps1 b/samples/client/petstore/powershell/src/PSPetstore/Private/PSHttpSignatureAuth.ps1 index d3fed6ead985..6cb2087ccf13 100644 --- a/samples/client/petstore/powershell/src/PSPetstore/Private/PSHttpSignatureAuth.ps1 +++ b/samples/client/petstore/powershell/src/PSPetstore/Private/PSHttpSignatureAuth.ps1 @@ -9,9 +9,9 @@ .SYNOPSIS Gets the headers for HTTP signature. .DESCRIPTION - Gets the headers for the http sigature. + Gets the headers for the http sigature. .PARAMETER Method - HTTP method + HTTP method .PARAMETER UriBuilder UriBuilder for url and query parameter .PARAMETER Body @@ -50,49 +50,43 @@ function Get-PSHttpSignedHeader { $TargetHost = $UriBuilder.Host $httpSigningConfiguration = Get-PSConfigurationHttpSigning $Digest = $null - + #get the body digest $bodyHash = Get-PSStringHash -String $Body -HashName $httpSigningConfiguration.HashAlgorithm if ($httpSigningConfiguration.HashAlgorithm -eq "SHA256") { $Digest = [String]::Format("SHA-256={0}", [Convert]::ToBase64String($bodyHash)) - } - elseif ($httpSigningConfiguration.HashAlgorithm -eq "SHA512") { + } elseif ($httpSigningConfiguration.HashAlgorithm -eq "SHA512") { $Digest = [String]::Format("SHA-512={0}", [Convert]::ToBase64String($bodyHash)) } - + $dateTime = Get-Date #get the date in UTC $currentDate = $dateTime.ToUniversalTime().ToString("r") foreach ($headerItem in $httpSigningConfiguration.HttpSigningHeader) { - - if ($headerItem -eq $HEADER_REQUEST_TARGET) { + + if ($headerItem -eq $HEADER_REQUEST_TARGET) { $requestTargetPath = [string]::Format("{0} {1}{2}", $Method.ToLower(), $UriBuilder.Path, $UriBuilder.Query) $HttpSignatureHeader.Add($HEADER_REQUEST_TARGET, $requestTargetPath) - } - elseif ($headerItem -eq $HEADER_CREATED) { + } elseif ($headerItem -eq $HEADER_CREATED) { $created = Get-PSUnixTime -Date $dateTime -TotalTime TotalSeconds $HttpSignatureHeader.Add($HEADER_CREATED, $created) - } - elseif ($headerItem -eq $HEADER_EXPIRES) { + } elseif ($headerItem -eq $HEADER_EXPIRES) { $expire = $dateTime.AddSeconds($httpSigningConfiguration.SignatureValidityPeriod) $expireEpocTime = Get-PSUnixTime -Date $expire -TotalTime TotalSeconds $HttpSignatureHeader.Add($HEADER_EXPIRES, $expireEpocTime) - } - elseif ($headerItem -eq $HEADER_HOST) { + } elseif ($headerItem -eq $HEADER_HOST) { $HttpSignedRequestHeader[$HEADER_HOST] = $TargetHost $HttpSignatureHeader.Add($HEADER_HOST.ToLower(), $TargetHost) - } - elseif ($headerItem -eq $HEADER_DATE) { + } elseif ($headerItem -eq $HEADER_DATE) { $HttpSignedRequestHeader[$HEADER_DATE] = $currentDate $HttpSignatureHeader.Add($HEADER_DATE.ToLower(), $currentDate) - } - elseif ($headerItem -eq $HEADER_DIGEST) { + } elseif ($headerItem -eq $HEADER_DIGEST) { $HttpSignedRequestHeader[$HEADER_DIGEST] = $Digest $HttpSignatureHeader.Add($HEADER_DIGEST.ToLower(), $Digest) - }elseif($RequestHeader.ContainsKey($headerItem)){ + } elseif($RequestHeader.ContainsKey($headerItem)) { $HttpSignatureHeader.Add($headerItem.ToLower(), $RequestHeader[$headerItem]) - }else{ + } else { throw "Cannot sign HTTP request. Request does not contain the $headerItem header." } } @@ -105,7 +99,7 @@ function Get-PSHttpSignedHeader { } #Concatinate headers value separated by new line $headerValuesString = $headerValuesList -join "`n" - + #Gets the hash of the headers value $signatureHashString = Get-PSStringHash -String $headerValuesString -HashName $httpSigningConfiguration.HashAlgorithm @@ -118,8 +112,7 @@ function Get-PSHttpSignedHeader { -HashAlgorithmName $httpSigningConfiguration.HashAlgorithm ` -KeyPassPhrase $httpSigningConfiguration.KeyPassPhrase ` -SigningAlgorithm $httpSigningConfiguration.SigningAlgorithm - } - elseif ($KeyType -eq "EC") { + } elseif ($KeyType -eq "EC") { $headerSignatureStr = Get-PSECDSASignature -ECKeyFilePath $httpSigningConfiguration.KeyFilePath ` -DataToSign $signatureHashString ` -HashAlgorithmName $httpSigningConfiguration.HashAlgorithm ` @@ -140,10 +133,10 @@ function Get-PSHttpSignedHeader { if ($HttpSignatureHeader.ContainsKey($HEADER_EXPIRES)) { $authorizationHeaderValue += [string]::Format(",expires={0}", $HttpSignatureHeader[$HEADER_EXPIRES]) } - - $authorizationHeaderValue += [string]::Format(",headers=""{0}"",signature=""{1}""", + + $authorizationHeaderValue += [string]::Format(",headers=""{0}"",signature=""{1}""", $headersKeysString , $headerSignatureStr) - + $HttpSignedRequestHeader[$HEADER_AUTHORIZATION] = $authorizationHeaderValue return $HttpSignedRequestHeader } @@ -153,7 +146,7 @@ function Get-PSHttpSignedHeader { Gets the RSA signature .DESCRIPTION - Gets the RSA signature for the http signing + Gets the RSA signature for the http signing .PARAMETER PrivateKeyFilePath Specify the API key file path .PARAMETER DataToSign @@ -174,11 +167,10 @@ function Get-PSRSASignature { [securestring]$KeyPassPhrase ) try { - + if ($hashAlgorithmName -eq "sha256") { $hashAlgo = [System.Security.Cryptography.HashAlgorithmName]::SHA256 - } - elseif ($hashAlgorithmName -eq "sha512") { + } elseif ($hashAlgorithmName -eq "sha512") { $hashAlgo = [System.Security.Cryptography.HashAlgorithmName]::SHA512 } @@ -194,31 +186,26 @@ function Get-PSRSASignature { if ($SigningAlgorithm -eq "RSASSA-PSS") { $signedBytes = $rsa.SignHash($DataToSign, $hashAlgo, [System.Security.Cryptography.RSASignaturePadding]::Pss) - } - else { + } else { $signedBytes = $rsa.SignHash($DataToSign, $hashAlgo, [System.Security.Cryptography.RSASignaturePadding]::Pkcs1) } - } - else { + } else { $rsa_provider_path = Join-Path -Path $PSScriptRoot -ChildPath "PSRSAEncryptionProvider.cs" $rsa_provider_sourceCode = Get-Content -Path $rsa_provider_path -Raw - Add-Type -TypeDefinition $rsa_provider_sourceCode - + Add-Type -TypeDefinition $rsa_provider_sourceCode + [System.Security.Cryptography.RSA]$rsa = [RSAEncryption.RSAEncryptionProvider]::GetRSAProviderFromPemFile($PrivateKeyFilePath, $KeyPassPhrase) - + if ($SigningAlgorithm -eq "RSASSA-PSS") { throw "$SigningAlgorithm is not supported on $($PSVersionTable.PSVersion)" - } - else { + } else { $signedBytes = $rsa.SignHash($DataToSign, $hashAlgo, [System.Security.Cryptography.RSASignaturePadding]::Pkcs1) } - } $signedString = [Convert]::ToBase64String($signedBytes) return $signedString - } - catch { + } catch { throw $_ } } @@ -228,7 +215,7 @@ function Get-PSRSASignature { Gets the ECDSA signature .DESCRIPTION - Gets the ECDSA signature for the http signing + Gets the ECDSA signature for the http signing .PARAMETER PrivateKeyFilePath Specify the API key file path .PARAMETER DataToSign @@ -255,7 +242,7 @@ function Get-PSECDSASignature { throw "key file path does not exist." } - if($PSVersionTable.PSVersion.Major -lt 7){ + if ($PSVersionTable.PSVersion.Major -lt 7) { throw "ECDSA key is not supported on $($PSVersionTable.PSVersion), Use PSVersion 7.0 and above" } @@ -269,27 +256,23 @@ function Get-PSECDSASignature { #$ecdsa = [System.Security.Cryptography.ECDsaCng]::New($cngKey) $ecdsa = [System.Security.Cryptography.ECDsaCng]::New() [int]$bytCount =0 - if(![string]::IsNullOrEmpty($KeyPassPhrase)){ + if (![string]::IsNullOrEmpty($KeyPassPhrase)) { $ecdsa.ImportEncryptedPkcs8PrivateKey($KeyPassPhrase,$keyBytes,[ref]$bytCount) + } else { + $ecdsa.ImportPkcs8PrivateKey($keyBytes,[ref]$bytCount) } - else{ - $ecdsa.ImportPkcs8PrivateKey($keyBytes,[ref]$bytCount) - } - + if ($HashAlgorithmName -eq "sha512") { $ecdsa.HashAlgorithm = [System.Security.Cryptography.CngAlgorithm]::Sha512 - } - else { + } else { $ecdsa.HashAlgorithm = [System.Security.Cryptography.CngAlgorithm]::Sha256 } $signedBytes = $ecdsa.SignHash($DataToSign) $signedString = [System.Convert]::ToBase64String($signedBytes) return $signedString - } - <# .Synopsis Gets the hash of string. @@ -301,7 +284,7 @@ function Get-PSECDSASignature { Specifies the hash name to calculate the hash, Accepted values are "SHA1", "SHA256" and "SHA512" It is recommneded not to use "SHA1" to calculate the Hash .Outputs -String + String #> Function Get-PSStringHash { param( @@ -311,9 +294,9 @@ Function Get-PSStringHash { [Parameter(Mandatory = $true)] [ValidateSet("SHA1", "SHA256", "SHA512")] $HashName - ) + ) $hashAlogrithm = [System.Security.Cryptography.HashAlgorithm]::Create($HashName) - $hashAlogrithm.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($String)) + $hashAlogrithm.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($String)) } <# @@ -365,7 +348,6 @@ function Get-PSCryptographicScheme { return $SigningAlgorithm } - <# .Synopsis Gets the key type from the pem file. @@ -396,20 +378,16 @@ function Get-PSKeyTypeFromFile { if ($key[0] -match $rsaPrivateKeyHeader -and $key[$key.Length - 1] -match $rsaPrivateFooter) { $KeyType = "RSA" - - } - elseif ($key[0] -match $ecPrivateKeyHeader -and $key[$key.Length - 1] -match $ecPrivateKeyFooter) { + } elseif ($key[0] -match $ecPrivateKeyHeader -and $key[$key.Length - 1] -match $ecPrivateKeyFooter) { $keyType = "EC" - } - elseif ($key[0] -match $ecPrivateKeyHeader -and $key[$key.Length - 1] -match $ecPrivateKeyFooter) { + } elseif ($key[0] -match $ecPrivateKeyHeader -and $key[$key.Length - 1] -match $ecPrivateKeyFooter) { <#this type of key can hold many type different types of private key, but here due lack of pem header - Considering this as EC key - #> + Considering this as EC key + #> #TODO :- update the key based on oid $keyType = "EC" - } - else { + } else { throw "Either the key is invalid or key is not supported" } - return $keyType -} \ No newline at end of file + return $keyType +} diff --git a/samples/client/petstore/powershell/src/PSPetstore/Private/PSRSAEncryptionProvider.cs b/samples/client/petstore/powershell/src/PSPetstore/Private/PSRSAEncryptionProvider.cs index 7a671929fb2b..451221fd8940 100644 --- a/samples/client/petstore/powershell/src/PSPetstore/Private/PSRSAEncryptionProvider.cs +++ b/samples/client/petstore/powershell/src/PSPetstore/Private/PSRSAEncryptionProvider.cs @@ -64,7 +64,7 @@ static byte[] ConvertPrivateKeyToBytes(String instr, SecureString keyPassPharse return binkey; } catch (System.FormatException) - { + { StringReader str = new StringReader(pvkstr); //-------- read PEM encryption info. lines and extract salt ----- @@ -234,7 +234,7 @@ static byte[] GetEncryptedKey(byte[] salt, SecureString secpswd, int count, int { // ---- Now hash consecutively for count times ------ if (j == 0) - result = data00; //initialize + result = data00; //initialize else { Array.Copy(result, hashtarget, result.Length); @@ -276,4 +276,4 @@ static byte[] DecryptKey(byte[] cipherData, byte[] desKey, byte[] IV) return decryptedData; } } -} \ No newline at end of file +} diff --git a/samples/client/petstore/powershell/src/PSPetstore/en-US/about_PSPetstore.help.txt b/samples/client/petstore/powershell/src/PSPetstore/en-US/about_PSPetstore.help.txt index c35d0e44240a..af56b5a29483 100644 --- a/samples/client/petstore/powershell/src/PSPetstore/en-US/about_PSPetstore.help.txt +++ b/samples/client/petstore/powershell/src/PSPetstore/en-US/about_PSPetstore.help.txt @@ -15,5 +15,5 @@ LONG DESCRIPTION Frameworks supported: - * PowerShell 3.0+ + * PowerShell 5.0 or later * .NET 4.0 or later From 9fb33088c60eb6eb369de3fb4b20752265086061 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Fri, 31 Jul 2020 17:16:58 +0800 Subject: [PATCH 2/2] add code to publish ps module --- .../src/main/resources/powershell/appveyor.mustache | 7 +++++++ samples/client/petstore/powershell/appveyor.yml | 7 +++++++ 2 files changed, 14 insertions(+) diff --git a/modules/openapi-generator/src/main/resources/powershell/appveyor.mustache b/modules/openapi-generator/src/main/resources/powershell/appveyor.mustache index 46e6d61028bd..f337f619ba0c 100644 --- a/modules/openapi-generator/src/main/resources/powershell/appveyor.mustache +++ b/modules/openapi-generator/src/main/resources/powershell/appveyor.mustache @@ -15,3 +15,10 @@ test_script: $host.SetShouldExit($Result.FailedCount) exit $Result.FailedCount } + - ps: | + if ($env:APPVEYOR_REPO_TAG -eq $true -and $env:NuGetApiKey -ne $null) + { + choco install NuGet.CommandLine + Install-PackageProvider -Name NuGet -Force + Publish-Module -NuGetApiKey $env:NuGetApiKey -Path .\ -Confirm:$False -Verbose + } diff --git a/samples/client/petstore/powershell/appveyor.yml b/samples/client/petstore/powershell/appveyor.yml index fab089d4d649..ec43839e3e3f 100644 --- a/samples/client/petstore/powershell/appveyor.yml +++ b/samples/client/petstore/powershell/appveyor.yml @@ -21,3 +21,10 @@ test_script: $host.SetShouldExit($Result.FailedCount) exit $Result.FailedCount } + - ps: | + if ($env:APPVEYOR_REPO_TAG -eq $true -and $env:NuGetApiKey -ne $null) + { + choco install NuGet.CommandLine + Install-PackageProvider -Name NuGet -Force + Publish-Module -NuGetApiKey $env:NuGetApiKey -Path .\ -Confirm:$False -Verbose + }