Advertisement
Guest User

IDGSecureChannel2

a guest
Apr 9th, 2013
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Function Get-IDGSecureChannelConfig {
  2.     $cfg = "" | select Password,RootFolder,PfxFile,CertCN,BCUrl,BCZipFile,BCFolder,BCDll,KeySize
  3.     $cfg.Password = "Password1"
  4.     $cfg.RootFolder = join-path $env:TEMP "Neptune Magic Stuff"
  5.     $cfg.PfxFile = Join-Path $cfg.RootFolder "IDGcert.pfx"
  6.     $cfg.CertCN = "IDG Secure Channel cert"
  7.     $cfg.KeySize = 2048
  8.     $cfg.BCUrl = "http://www.bouncycastle.org/csharp/download/bccrypto-net-1.7-bin.zip"
  9.     $cfg.BCZipFile = Join-Path $cfg.RootFolder "bc.zip"
  10.     $cfg.BCFolder = Join-Path $cfg.RootFolder "bc"
  11.     $cfg.BCDll = Join-Path $cfg.BCFolder "BouncyCastle.Crypto.dll"
  12.     mkdir $cfg.BCFolder -force -ErrorAction SilentlyContinue | Out-Null
  13.     $cfg
  14. }
  15. Function Get-IDGSecureChannelPublicKey {
  16.     [cmdletbinding()]
  17.     Param()
  18.     $cfg = Get-IDGSecureChannelConfig
  19.     if( -not (test-path $cfg.BCDll)) {
  20.         Write-Verbose "Downloading BouncyCastle Crypto API..."
  21.         $wc = new-object System.Net.WebClient
  22.         $wc.DownloadFile($cfg.BCUrl ,$cfg.BCZipFile)
  23.         # System.IO.Compression.FileSystem only in .NET 4.5
  24.         #add-type -AssemblyName System.IO.Compression.FileSystem | out-null
  25.         #[io.compression.zipfile]::ExtractToDirectory($cfg.BCZipFile,$cfg.BCFolder)
  26.         $shellCom = New-Object -ComObject Shell.Application
  27.         $filesInZip = $shellCom.NameSpace($cfg.BCZipFile).items()
  28.         $shellCom.NameSpace($cfg.BCFolder).Copyhere($filesInZip)
  29.     }
  30.     Write-Verbose "Loading BouncyCastle Crypto API..."
  31.     Add-Type -Path $cfg.BCDll | out-null
  32.  
  33.     if( -not (test-path $cfg.PfxFile)) {
  34.         Write-Verbose "No PFX File, creating new PFX file..."
  35.  
  36.         $keyGen = New-Object Org.BouncyCastle.Crypto.Generators.RsaKeyPairGenerator
  37.         $secRandom = new-object Org.BouncyCastle.Security.SecureRandom
  38.         $KeyGenParam = new-object Org.BouncyCastle.Crypto.KeyGenerationParameters $secRandom,$cfg.KeySize
  39.         $keyGen.Init($KeyGenParam)
  40.  
  41.         $keys = $keygen.GenerateKeyPair()
  42.         $certGen = New-Object Org.BouncyCastle.X509.X509V3CertificateGenerator
  43.         $dnName = New-Object Org.BouncyCastle.Asn1.X509.X509Name("CN=$($cfg.CertCN)")
  44.  
  45.         $now = [DateTime]::Today
  46.         $certGen.SetSerialNumber([Org.BouncyCastle.Math.BigInteger]::ValueOf(1));
  47.         $certGen.SetIssuerDN($dnName);
  48.         $certGen.SetNotBefore($now);
  49.         $certGen.SetNotAfter($now.AddYears(1));
  50.         $certGen.SetSubjectDN($dnName);
  51.         $certGen.SetPublicKey($keys.Public);
  52.         $certGen.SetSignatureAlgorithm("SHA1WITHRSA");
  53.         $cert = $certGen.Generate($keys.Private);
  54.  
  55.         $store = New-Object Org.BouncyCastle.Pkcs.Pkcs12Store
  56.         $keyEntry = new-object Org.BouncyCastle.Pkcs.AsymmetricKeyEntry $keys.Private
  57.         $certArray = New-Object Org.BouncyCastle.Pkcs.X509CertificateEntry[] 1
  58.         $certArray[0] = New-Object Org.BouncyCastle.Pkcs.X509CertificateEntry $cert
  59.         $store.SetKeyEntry($cfg.CertCN, $keyEntry, $certArray);
  60.  
  61.         $stream = New-Object System.IO.MemoryStream
  62.         $store.Save($stream, $cfg.Password.ToCharArray(), $secRandom);
  63.            
  64.         $stream.Flush()
  65.         $length = [int]$stream.Position
  66.         [byte[]]$data = $stream.GetBuffer()
  67.         $stream.Close()
  68.         $stream.Dispose()
  69.            
  70.         $fstream = [IO.File]::Create($cfg.PfxFile)
  71.         $fstream.Write($data, 0, $data.Length)
  72.         $fstream.Close()
  73.         $fstream.Dispose()
  74.     } else {
  75.         Write-Verbose "Has PFX File, loading cert from PFX file..."
  76.         $stream = [IO.File]::OpenRead($cfg.PfxFile)
  77.         $store = New-Object Org.BouncyCastle.Pkcs.Pkcs12Store    
  78.         $store.Load($stream, $cfg.Password.ToCharArray())
  79.         $stream.Close()
  80.         $stream.Dispose()
  81.         $certContainer = $store.GetCertificate($cfg.CertCN)
  82.         $cert = $certContainer.Certificate
  83.     }
  84.     $pubKeyObj = ""| select PublicKey
  85.     $pubKeyObj.PublicKey = [convert]::ToBase64String($cert.GetPublicKey().Modulus.ToByteArray())
  86.     $pubKeyObj
  87. }
  88. Function ConvertTo-IDGSecureChannelString {
  89.     param(
  90.         [Parameter(Mandatory=$true)]
  91.         [string]$PublicKey,
  92.         [Parameter(Mandatory=$true,ValueFromPipeLine=$true)]
  93.         [string]$Message
  94.     )
  95.     $modulusBytes = [convert]::FromBase64String($PublicKey)
  96.     $modulus = New-Object Org.BouncyCastle.Math.BigInteger @(,$modulusBytes)
  97.     $exponent = [Org.BouncyCastle.Math.BigInteger]::ValueOf(65537)
  98.     $rsaKeyParams = New-Object Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters $false,$modulus,$exponent
  99.     $rsaEngine = New-Object Org.BouncyCastle.Crypto.Engines.RsaEngine
  100.     $rsaEngine.Init($true,$rsaKeyParams)
  101.     $messageData = [System.Text.UTF8Encoding]::UTF8.GetBytes($message)
  102.  
  103.     $inputBlockSize=$rsaEngine.getInputBlockSize() # ??????????? + 1
  104.     $offset = 0
  105.     $continue=$true
  106.     $stream = New-Object System.IO.MemoryStream
  107.     do {
  108.         if(($offset +1) * $inputBlockSize -lt $messageData.Length) {            
  109.             $toRead = $inputBlockSize
  110.         } else {
  111.             $toRead = $messageData.Length - $offset * $inputBlockSize
  112.             $continue=$false
  113.         }        
  114.         $encryptedBuffer = $rsaEngine.processBlock($messageData,$offset * $inputBlockSize ,$toRead);
  115.         $stream.Write($encryptedBuffer,0,$encryptedBuffer.Length)
  116.         $offset++        
  117.     } while($continue)
  118.     $stream.Flush()
  119.     $encryptedData = $stream.GetBuffer()
  120.     $stream.Close()
  121.     $stream.Dispose()
  122.     $encryptedString = [convert]::ToBase64String($encryptedData)
  123.     $encryptedString
  124. }
  125. Function ConvertFrom-IDGSecureChannelString {
  126.     param(
  127.         [Parameter(Mandatory=$true,ValueFromPipeLine=$true)]
  128.         [string]$IDGSecureChannelString
  129.     )
  130.     $cfg = Get-IDGSecureChannelConfig
  131.     $stream = [IO.File]::OpenRead($cfg.PfxFile)
  132.     $store = New-Object Org.BouncyCastle.Pkcs.Pkcs12Store    
  133.     $store.Load($stream, $cfg.Password.ToCharArray())
  134.     $stream.Close()
  135.     $stream.Dispose()
  136.     $privKey = $store.GetKey($cfg.CertCN).Key
  137.  
  138.     $rsaKeyParams = New-Object Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters $true,$privKey.Modulus,$privKey.Exponent
  139.     $rsaEngine = New-Object Org.BouncyCastle.Crypto.Engines.RsaEngine
  140.     $rsaEngine.Init($false,$rsaKeyParams)
  141.     $messageData = [convert]::FromBase64String($IDGSecureChannelString)
  142.  
  143.     $inputBlockSize=$rsaEngine.getInputBlockSize() # ??????????? + 1
  144.     $offset = 0
  145.     $continue=$true
  146.     $stream = New-Object System.IO.MemoryStream
  147.     do {
  148.         if(($offset +1) * $inputBlockSize -lt $messageData.Length) {            
  149.             $toRead = $inputBlockSize
  150.         } else {
  151.             $toRead = $messageData.Length - $offset * $inputBlockSize
  152.             $continue=$false
  153.         }        
  154.         $decryptedBuffer = $rsaEngine.processBlock($messageData,$offset * $inputBlockSize ,$toRead);
  155.         $stream.Write($decryptedBuffer,0,$decryptedBuffer.Length)
  156.         $offset++        
  157.     } while($continue)
  158.     $stream.Flush()
  159.     $decryptedData = $stream.GetBuffer()
  160.     $stream.Close()
  161.     $stream.Dispose()
  162.     $decryptedString = [System.Text.UTF8Encoding]::UTF8.GetString($decryptedData)
  163.     if($decryptedString.IndexOf("`0") -gt -1){
  164.         $decryptedString = $decryptedString.Substring(0,$decryptedString.IndexOf("`0"))
  165.     }
  166.     $decryptedString              
  167. }
  168. Export-ModuleMember -Function "Get-IDGSecureChannelPublicKey","ConvertFrom-IDGSecureChannelString","ConvertTo-IDGSecureChannelString"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement