Last active
December 15, 2020 21:29
-
-
Save ciis0/d631e5526fab765ab1bc99a5467d05d2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# PowerShell-Based diffie-hellmann key exchange | |
# christoph.2.schulz@atos.net, Dec 2020. | |
# first, on both machines execute the script without parameters | |
# exchange public keys between machines | |
# on each machine run script again with (own) private key and (other) public key arguments set accordingly. | |
# inspired by https://gist.github.com/FrankSpierings/a5af505068073feea0ae | |
using namespace System.Security.Cryptography | |
param( | |
[Parameter(HelpMessage="Local private key, base64-encoded. Leave empty to generate.")] | |
[Alias("MyPrivate","Key")] | |
[String] | |
$KeyParam = "", | |
[Parameter(HelpMessage="Remote public key, base64-encoded.")] | |
[Alias("OtherPublic","Pub")] | |
[String] | |
$PubParam, | |
[Switch] | |
[Parameter(HelpMessage="Compress JSON output into a single line")] | |
$Compress = $false | |
) | |
if($KeyParam -eq "") { # generate key | |
$kgp = New-Object CngKeyCreationParameters | |
$kgp.ExportPolicy = [CngExportPolicies]::AllowPlaintextExport | |
[CngKey]$Key = [CngKey]::Create([CngAlgorithm]::ECDiffieHellmanP256, [NullString]::Value, $kgp) | |
return @{ | |
key=[Convert]::ToBase64String($Key.Export([CngKeyBlobFormat]::EccPrivateBlob)); | |
pub=[Convert]::ToBase64String($Key.Export([CngKeyBlobFormat]::EccPublicBlob)); | |
} | %{ | |
if($Compress){ | |
$_ | convertto-json -compress | |
} else { | |
$_ | convertto-json | |
} | |
} | |
} else { # derive secret | |
$Key = [CngKey]::Import([Convert]::FromBase64String($KeyParam), [CngKeyBlobFormat]::EccPrivateBlob) | |
[ECDiffieHellmanCng]$Dh = New-Object ECDiffieHellmanCng($Key) | |
[CngKey]$OtherPub = [CngKey]::Import([Convert]::FromBase64String($PubParam), [CngKeyBlobFormat]::EccPublicBlob) | |
[Byte[]] $SharedSecret = $Dh.DeriveKeyMaterial($OtherPub) | |
return @{ | |
secret=[Convert]::ToBase64String($SharedSecret) | |
} | %{ | |
if($Compress){ | |
$_ | convertto-json -compress | |
} else { | |
$_ | convertto-json | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment