<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="https://www.w3.org/2005/Atom" xmlns:sy="https://purl.org/rss/1.0/modules/syndication/" xmlns:dc="https://purl.org/dc/elements/1.1/" xmlns:content="https://purl.org/rss/1.0/modules/content/" xmlns:wfw="https://wellformedweb.org/CommentAPI/" xmlns:slash="https://purl.org/rss/1.0/modules/slash/"
  version="2.0">
  <channel>
    <title>Rohit Minni’s Weblog – Managing Hybrid Cloud Infrastructure and Solutions</title>
    <atom:link
      href="https://docs.microsoft.com/archive/blogs/rohit-minni/feed.xml"
      rel="self"
      type="application/rss+xml" />
    <link>https://docs.microsoft.com/archive/blogs/rohit-minni/feed.xml</link>
    <description>All about Azure, Office 365 and Building Secure Infrastructure Solutions</description>
    <lastBuildDate>Wed, 13 Jun 2018 20:43:18 GMT</lastBuildDate>
    <language>en-US</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <item>
      <title>"CredSSP encryption oracle remediation" error when RDP to a Windows VM in Azure</title>
      <link>https://docs.microsoft.com/archive/blogs/rohit-minni/credssp-encryption-oracle-remediation-error-when-rdp-to-a-windows-vm-in-azure</link>
      <pubDate>Tue, 12 Jun 2018 11:14:05 GMT</pubDate>
      <dc:creator><![CDATA[Rohit Minni]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.technet.microsoft.com/rohit-minni/?p=165</guid>
      <description><![CDATA[Recently, we have been seeing this error message "CredSSP encryption oracle remediation" error when...]]></description>
      <content:encoded><![CDATA[Recently, we have been seeing this error message <strong>"CredSSP encryption oracle remediation" error when RDP to a Windows VM in Azure quite</strong> frequently which does not allow you to RDP/Login into your Azure VM. Full documentation and root cause analysis of the issue is mentioned in this <a href="https://support.microsoft.com/en-us/help/4295591/credssp-encryption-oracle-remediation-error-when-to-rdp-to-azure-vm">article released by Microsoft Support</a>

Do not worry if you run into this issue as resolving this on your Azure VM is pretty simple and can be done very easily from your azure portal. Steps to resolve this are:
<ol>
 	<li>Login into <a href="https://portal.azure.com">https://portal.azure.com</a></li>
 	<li>Navigate to the Azure Virtual Machine tab and go to the VM that is giving this error</li>
 	<li>Now under operations, select the Run Command option which will give you the option to run a PowerShell script</li>
 	<li><img src="https://msdnshared.blob.core.windows.net/media/2018/06/runcmd.png" alt="" width="3000" height="1133" class="alignnone size-full wp-image-175" /></li>
 	<li>In the PowerShell script section, type in the below two lines and click on run</li>
</ol>
<pre>REG ADD HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\System\CredSSP\Parameters\ /v AllowEncryptionOracle /t REG_DWORD /d 2

Set-ItemProperty -Path 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System\CredSSP\Parameters' -name "AllowEncryptionOracle" 2 -Type DWord</pre>
&nbsp;

Now on your own machine (client machine), follow the below steps:
<ol>
 	<li>On the client that has the CredSSP update installed, run <strong>gpedit.msc</strong>, and then browse to <strong>Computer Configuration </strong>&gt;<strong> Administrative Templates </strong>&gt;<strong> System </strong>&gt;<strong> Credentials Delegation</strong> in the navigation pane.</li>
 	<li>Change the <strong>Encryption Oracle Remediation policy</strong> to <strong>Enabled</strong>, and then change <strong>Protection Level</strong> to <strong>Vulnerable</strong>.</li>
</ol>
If needed, please restart the server and now when you try to RDP into your Azure VM you will be able to login and complete the connection. Please note that it is highly recommended to patch your VMs and follow the latest guidelines that are mentioned in the <a href="https://support.microsoft.com/en-us/help/4295591/credssp-encryption-oracle-remediation-error-when-to-rdp-to-azure-vm">Microsoft Support Article</a>.

-Cheers]]></content:encoded>
    </item>
    <item>
      <title>Performing SQL Bulk Copy with Azure Automation/PowerShell while modifying source data</title>
      <link>https://docs.microsoft.com/archive/blogs/rohit-minni/performing-sql-bulk-copy-with-azure-automationpowershell-while-modifying-source-data</link>
      <pubDate>Wed, 27 Dec 2017 13:27:28 GMT</pubDate>
      <dc:creator><![CDATA[Rohit Minni]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.technet.microsoft.com/rohit-minni/?p=155</guid>
      <description><![CDATA[In this blog, I will be going over how to use AzureAutomation/PowerShell to perform bulk operations...]]></description>
      <content:encoded><![CDATA[In this blog, I will be going over how to use AzureAutomation/PowerShell to perform bulk operations using bulk copy in SQL Server instances and as we perform the bulk copy, I will also be editing the source data and adding some logging information to the rows in the database.

The script can be downloaded from my technet blog post <a href="https://gallery.technet.microsoft.com/Performing-SQL-Bulk-Copy-21eb5fe3">here</a>

For simplicity and more usability, consider I have a CSV file with source data that I want to insert in a database table in SQL Server. The CSV in this example has the following headers:

Group,PrimarySMTPAddress

Now, while performing the bulk insert, I want to add additional columns like Id and GUID. Normally all of these operations is super time consuming in Azure Automation and a lot of times this results into the script host running out of memory and the script fails to complete. Normally you would get an error like:

“The job action 'Activate' cannot be run, because the process stopped unexpectedly. The job action was attempted 3 times”

Normally, you would write a basic bulk copy script like this where "BulkCopyTo-SQLServer" is a placeholder logic for your Bulk Insert/Update:

&nbsp;
<div class="scriptcode">
<div class="pluginEditHolder">
<blockquote>
<div class="title"><span>PowerShell</span></div>
<pre class="powershell"><span class="powerShell__variable">$CSVData</span> = <span class="powerShell__cmdlets">Import-Csv</span> <span class="powerShell__operator">-</span>Path <span class="powerShell__variable">$CSVPath</span> <span class="powerShell__operator">-</span>Delimiter <span class="powerShell__string">','</span> 
 
<span class="powerShell__variable">$dtable</span> = <span class="powerShell__variable">$CSVData</span> <span class="powerShell__operator">|</span> Out<span class="powerShell__operator">-</span>DataTable  
 
BulkCopyTo<span class="powerShell__operator">-</span>SQLServer <span class="powerShell__operator">-</span><span class="powerShell__keyword">Data</span> <span class="powerShell__variable">$dtable</span> 
</pre>
</blockquote>
</div>
</div>
<div class="endscriptcode"></div>
&nbsp;

But this consumes tremendous amount of memory in all the three steps. Instead we should write the above as below to do everything without creating any intermediate variables.

&nbsp;
<div class="scriptcode">
<div class="pluginEditHolder">
<blockquote>
<div class="title"><span>PowerShell</span></div>
<pre class="powershell"><span class="powerShell__cmdlets">Import-Csv</span> <span class="powerShell__operator">-</span>Path <span class="powerShell__variable">$CSVPath</span> <span class="powerShell__operator">-</span>Delimiter <span class="powerShell__string">','</span> <span class="powerShell__operator">|</span> Out<span class="powerShell__operator">-</span>DataTable <span class="powerShell__operator">|</span> BulkCopyTo<span class="powerShell__operator">-</span>SQLServer</pre>
</blockquote>
</div>
</div>
<div class="endscriptcode"></div>
&nbsp;

With the attached script, the way that its designed is that it wont be memory intensive and yet bulk process and copy the rows into SQL - That's the beauty of PowerShell.

I was able to insert about a 1,00,000 rows within couple of seconds with this script, let me know if you guys have comments or feedback!

&nbsp;

Cheers!]]></content:encoded>
    </item>
    <item>
      <title>Remoting into Azure ARM Virtual Machines using Powershell</title>
      <link>https://docs.microsoft.com/archive/blogs/rohit-minni/remoting-into-azure-arm-virtual-machines-using-powershell</link>
      <pubDate>Wed, 18 Jan 2017 15:02:29 GMT</pubDate>
      <dc:creator><![CDATA[Rohit Minni]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.technet.microsoft.com/rohit-minni/?p=146</guid>
      <description><![CDATA[You can find all the referenced scripts in my TechNet Gallery and download them from here.

With...]]></description>
      <content:encoded><![CDATA[You can find all the referenced scripts in my TechNet Gallery and download them from <strong><a href="https://gallery.technet.microsoft.com/Remoting-into-Azure-ARM-ebcec7c3">here</a></strong>.

With the introduction of Azure Resource Manager (ARM), there has been a slight change in the way we remote into Azure Virtual Machines. If you've worked with Azure Service Management Virtual Machines, you would recollect that the default Powershell remoting (WinRM) endpoint was configured by default. With the ARM Virtual Machines this does not come by default. In Azure Service Management Virtual Machines had the WinRM pre-configured whereas in ARM Virtual Machines this is not the case. The scripts attached in this post will help you achieve the same so that you can remote into your ARM Virtual Machines. These scripts are targeted specifically for Azure Automation although, you can modify them as per your need in case you want to run it normally with Powershell. The scripts are in both the Azure Automation supported formats : Workflows as well as Powershell Scripts.

&nbsp;

In a nutshell, there are 4 major steps required to configure and remote into your ARM Virtual Machine.
<ol type="1">
 	<li><span>Configure your Virtual Machine's WinRM listener to listen to HTTPS requests</span></li>
 	<li><span>Open the firewall port for the incoming traffic</span></li>
 	<li><span>Add a Network Security Group Rule to allow inbound requests into the Virtual Machine</span></li>
 	<li><span>Get the public IP Address of the Virtual Machine and remote into it</span></li>
</ol>
&nbsp;

There are four scripts attached with this post namely:
<ol type="1">
 	<li><span>Connect-AzureARMVM (PowerShell Workflow) which performs steps 1,2,3 and 4 that were listed above</span></li>
 	<li><span>Remote-AzureARMVM (PowerShell Workflow) which uses the IP Address passed from Connect-AzureARMVM to remote into the VM and perform any operation</span></li>
 	<li>Connect-AzureARMVMPS (PowerShell Script) which performs steps 1,2,3 and 4 that were listed above</li>
 	<li>Remote-AzureARMVMPS (PowerShell Script) which uses the IP Address passed from Connect-AzureARMVM to remote into the VM and perform any operation</li>
</ol>
&nbsp;

That being said, there are basically two scenarios that arise in this case when you are using this script.
<ul type="disc">
 	<li><span>ARM Virtual Machine that has a standard storage account.</span>
<ol type="a">
 	<li><span>The two attached scripts can be used as is in this scenario.</span></li>
 	<li><span>The script uses Custom Script Extension to configure the WinRM Listener, enable the firewall rule in the VM and stores this configuration script in a Script container in the storage account where the VM is hosted so that the Custom Script Extension can pick it up from there.</span></li>
</ol>
</li>
 	<li><span>ARM Virtual Machine that has a premium storage account.</span>
<ol type="a">
 	<li><span>To configure such Virtual Machines, we will have to perform the steps 1,2,3 and 4 manually by running the following code block in a powershell prompt on the VM</span></li>
</ol>
</li>
</ul>
<div class="scriptcode">
<div class="pluginEditHolder">
<div class="title"><span>PowerShell</span></div>
<pre class="powershell"><code><span class="powerShell__com">#POWERSHELL TO EXECUTE ON REMOTE SERVER BEGINS HERE </span> 
<span class="powerShell__variable">$DNSName</span> = <span class="powerShell__variable">$env</span>:COMPUTERNAME 
<span class="powerShell__com">#Ensure PS remoting is enabled, although this is enabled by default for Azure VMs</span> 
Enable<span class="powerShell__operator">-</span>PSRemoting <span class="powerShell__operator">-</span>Force   
<span class="powerShell__com">#Create rule in Windows Firewall</span> 
New<span class="powerShell__operator">-</span>NetFirewallRule <span class="powerShell__operator">-</span>Name <span class="powerShell__string">"WinRM HTTPS"</span> <span class="powerShell__operator">-</span>DisplayName <span class="powerShell__string">"WinRM HTTPS"</span> <span class="powerShell__operator">-</span>Enabled True <span class="powerShell__operator">-</span>Profile <span class="powerShell__string">"Any"</span> <span class="powerShell__operator">-</span>Action <span class="powerShell__string">"Allow"</span> <span class="powerShell__operator">-</span>Direction <span class="powerShell__string">"Inbound"</span> <span class="powerShell__operator">-</span>LocalPort 5986 <span class="powerShell__operator">-</span>Protocol <span class="powerShell__string">"TCP"</span>    
<span class="powerShell__com">#Create Self Signed certificate and store thumbprint</span> 
<span class="powerShell__variable">$thumbprint</span> = (New<span class="powerShell__operator">-</span>SelfSignedCertificate <span class="powerShell__operator">-</span>DnsName <span class="powerShell__variable">$DNSName</span> <span class="powerShell__operator">-</span>CertStoreLocation Cert:\LocalMachine\My).Thumbprint   
<span class="powerShell__com">#Run WinRM configuration on command line. DNS name set to computer hostname, you may wish to use a FQDN</span> 
<span class="powerShell__variable">$cmd</span> = <span class="powerShell__string">"winrm create winrm/config/Listener?Address=*+Transport=HTTPS @{Hostname="</span><span class="powerShell__string">"$DNSName"</span><span class="powerShell__string">"; CertificateThumbprint="</span><span class="powerShell__string">"$thumbprint"</span><span class="powerShell__string">"}"</span> 
cmd.exe <span class="powerShell__operator">/</span>C <span class="powerShell__variable">$cmd</span>   
<span class="powerShell__com">#POWERSHELL TO EXECUTE ON REMOTE SERVER ENDS HERE</span></code></pre>
</div>
</div>
<div class="endscriptcode"></div>
<span> </span>

&nbsp;
<ul>
 	<li>Add a Network Security Group Rule for the VM on port 5986</li>
</ul>
<ol type="a"></ol>
<img id="153300" src="https://gallery.technet.microsoft.com/scriptcenter/site/view/file/153300/1/inbound.PNG" alt="Machine generated alternative text:10;Inbound security rules 10;earch inbo d se curity rules 10;PRIORITY 10;1000 10;1100 10;NAME 10;default-allow-rap 10;WinRM HTTPS 10;SOURCE 10;DESTINATION 10;SERVICE 10;RDP (TCP/3389) 10;WinRM (TCP/5986) 10;Allow 10;Allow " width="844" height="254" />

&nbsp;
<ul>
 	<li>You can then fetch the Public IP Address of the VM and remote into it in the same way as described earlier.</li>
</ul>
&nbsp;

&nbsp;
<div class="scriptcode">
<div class="pluginEditHolder">
<div class="title"><span>PowerShell</span></div>
<pre class="powershell"><span class="powerShell__variable">$IpAddress</span> = .\Connect<span class="powerShell__operator">-</span>AzureARMVMPS.ps1 <span class="powerShell__operator">-</span>AzureSubscriptionId <span class="powerShell__variable">$AzureSubscriptionId</span> <span class="powerShell__operator">-</span>AzureOrgIdCredentialName <span class="powerShell__variable">$AzureOrgIdCredentialName</span> <span class="powerShell__operator">-</span>ResourceGroupName <span class="powerShell__variable">$ResourceGroupName</span> <span class="powerShell__operator">-</span>VMName <span class="powerShell__variable">$VMName</span>   
    Write<span class="powerShell__operator">-</span>Output <span class="powerShell__string">"The IP Address is $IpAddress. Attempting to remote into the VM.."</span> 
    <span class="powerShell__keyword">if</span>(<span class="powerShell__variable">$IpAddress</span> <span class="powerShell__operator">-</span>ne <span class="powerShell__variable">$null</span>) 
    { 
           
            <span class="powerShell__variable">$sessionOptions</span> = New<span class="powerShell__operator">-</span>PSSessionOption <span class="powerShell__operator">-</span>SkipCACheck <span class="powerShell__operator">-</span>SkipCNCheck                 
            Invoke<span class="powerShell__operator">-</span>Command <span class="powerShell__operator">-</span>ComputerName <span class="powerShell__variable">$IpAddress</span> <span class="powerShell__operator">-</span>Credential <span class="powerShell__variable">$VMCredential</span> <span class="powerShell__operator">-</span>UseSSL <span class="powerShell__operator">-</span>SessionOption <span class="powerShell__variable">$sessionOptions</span> <span class="powerShell__operator">-</span>ScriptBlock {  
            <span class="powerShell__com">#Code to be executed in the remote session goes here</span> 
            <span class="powerShell__variable">$hostname</span> = hostname 
            Write<span class="powerShell__operator">-</span>Output <span class="powerShell__string">"Hostname : $hostname"</span> 
            } 
 
    }</pre>
</div>
</div>
<div class="endscriptcode"></div>
<div class="endscriptcode">Please Note: A pre-requisite to run these scripts is to have the Global Modules installed in your Azure Automation Account which at the time of writing this article was 1.0.3. You may have to manually download and upload the AzureRM.Network Module v(1.0.3) into your Automation Account if you dont have it already. Ensure that all your modules are of the same version.</div>
&nbsp;
<ol type="a"></ol>
&nbsp;

Cheers!]]></content:encoded>
    </item>
    <item>
      <title>Getting Daily and Monthly Azure Billing Information for multiple subscriptions</title>
      <link>https://docs.microsoft.com/archive/blogs/rohit-minni/getting-daily-and-monthly-azure-billing-information-for-multiple-subscriptions</link>
      <pubDate>Sun, 15 Jan 2017 01:26:05 GMT</pubDate>
      <dc:creator><![CDATA[Rohit Minni]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.technet.microsoft.com/rohit-minni/?p=135</guid>
      <description><![CDATA[The Visual Studio Solution I recently published in the TechNet Gallery here contains a console...]]></description>
      <content:encoded><![CDATA[The Visual Studio Solution I recently published in the TechNet Gallery <a href="https://gallery.technet.microsoft.com/Getting-Daily-and-Monthly-e0c6868f">here</a> contains a console application that will help you collect data reports for daily and monthly Azure Consumption for multiple subscriptions. To get started, you need to replace the values in App.Config in WebJobBillingData Project. Code execution starts from Program.cs which initially gets the daily consumption and later on gets the monthly consumption of your Azure Subscription. You can modify the code to give you custom reports as well. This whole solution is a simple extension to the Azure Usage and Billing Solution available in GitHub and it gives you the specific usage and billing information which you can send out as an email using Azure Automation. I will be publishing a guide on how to do that very soon.

&nbsp;]]></content:encoded>
    </item>
    <item>
      <title>Authenticating to Services by storing credentials in Azure Key Vault</title>
      <link>https://docs.microsoft.com/archive/blogs/rohit-minni/authenticating-to-services-by-storing-credentials-in-azure-key-vault</link>
      <pubDate>Fri, 13 Jan 2017 14:56:51 GMT</pubDate>
      <dc:creator><![CDATA[Rohit Minni]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.technet.microsoft.com/rohit-minni/?p=85</guid>
      <description><![CDATA[Almost all the time we face this challenge of maintaining a central repository for storing the...]]></description>
      <content:encoded><![CDATA[Almost all the time we face this challenge of maintaining a central repository for storing the credentials, certificates and access keys to authenticate to the various online services. In this blog post I am going to cover various authentication scenarios that can be achieved by storing credentials and certificates in Azure Key Vault and how you can use them to authenticate your services like Azure, Office 365 or any other OAuth/Service provider.

The two major types of credentials we use for authenticating using Key Vault are:
<ol>
 	<li>Username and Password OR Client ID and Client Secret for Azure Service Principal authentication</li>
 	<li>Certificate authentication</li>
</ol>
The way this will work is that your code will call the Key Vault service to fetch the credential you wish to retrieve. Once key vault returns this, you can use this in your code for further authenticating to your services. The pre-requisite for this is that you have a key vault created in azure and that you grant appropriate access to the vault to your service principal/user in the context of which your code will connect to Azure Key Vault. Lets assume for this demo that your vault name is "RohitMinni".
<h3><span style="text-decoration: underline"><em><strong>Username and Password OR Client ID and Client Secret Authentication</strong></em></span></h3>
Login to the azure portal and create secrets that represent "username" and "password" as shown in the below figure. Give the appropriate username and password values when you create the secrets. In this example it is o365username and o365password

<img src="https://msdnshared.blob.core.windows.net/media/2017/01/img1.png" alt="img1" width="519" height="319" class="alignnone wp-image-95" />

&nbsp;
<h3><span style="text-decoration: underline"><em><strong>Certificate Authentication</strong></em></span></h3>
Run the following PowerShell code to create and upload a certificate in your Key Vault. Also make sure to upload the .cer file as a management certificate in the Azure Management Portal (<a href="https://manage.windowsazure.com">https://manage.windowsazure.com</a>).

<code>$cert = New-SelfSignedCertificate -DnsName TestCertificate -CertStoreLocation "cert:\LocalMachine\My"</code>
<code> $certName = "testcertificate"</code>
<code> $passwordText = "pass@word1"</code>
<code> $vaultName = "vaultname"</code>
<code> $password = ConvertTo-SecureString -String $passwordText -Force -AsPlainText</code>
<code> Export-PfxCertificate -Cert $cert -FilePath ".\$certName.pfx" -Password $password</code>
<code> Export-Certificate -Type CERT -Cert $cert -FilePath ".\$certName.cer"</code>
<code> $servicePrincipalSecpasswd = ConvertTo-SecureString "Client Secret" -AsPlainText -Force</code>
<code> $servicePrincialCred = New-Object System.Management.Automation.PSCredential ("ClientID@yourdomain.onmicrosoft.com", $servicePrincipalSecpasswd)</code>
<code> $TenantID = "Tenant ID"</code>
<code> Login-AzureRmAccount -ServicePrincipal -Credential $servicePrincialCred -TenantId $TenantID</code>

<code>cd $env:TEMP</code>
<code> $pfxFilePath = '.\$certName.pfx'</code>
<code> $flag = [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable</code>
<code> $collection = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection</code>
<code> $collection.Import($pfxFilePath, $passwordText, $flag)</code>
<code> $pkcs12ContentType = [System.Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12</code>
<code> #$clearBytes = $collection.Export($pkcs12ContentType)</code>
<code> $clearBytes = $collection.Export($pkcs12ContentType,$pwd)</code>
<code> $fileContentEncoded = [System.Convert]::ToBase64String($clearBytes)</code>
<code> $secret = ConvertTo-SecureString -String $fileContentEncoded -AsPlainText –Force</code>
<code> $secretContentType = 'application/x-pkcs12'</code>
<code> Set-AzureKeyVaultSecret -VaultName $vaultName -Name 'certificate' -SecretValue $Secret -ContentType $secretContentType</code>

<img src="https://msdnshared.blob.core.windows.net/media/2017/01/img2.png" alt="img2" width="530" height="451" class="alignnone wp-image-105" />

&nbsp;

Now that we have the basic setup completed, we will get to the part where we use these credentials in some C# code.

Please find below some code snippets that would allow you to connect to your Azure Key Vault, fetch the credentials you just stored and use them to interact with some Azure or Office 365 services to consume their REST API's or Client Libraries.
<pre style="font-family: Consolas;font-size: 13;color: black;background: white"><span style="color: blue">public</span> <span style="color: blue">static</span> <span style="color: blue">async</span> <span style="color: #2b91af">Task</span>&lt;<span style="color: blue">string</span>&gt; GetToken(<span style="color: blue">string</span> authority, <span style="color: blue">string</span> resource, <span style="color: blue">string</span> scope)
{
 
    <span style="color: blue">var</span> authContext = <span style="color: blue">new</span> Microsoft.IdentityModel.Clients.ActiveDirectory.<span style="color: #2b91af">AuthenticationContext</span>(authority);
    <span style="color: #2b91af">ClientCredential</span> clientCred = <span style="color: blue">new</span> <span style="color: #2b91af">ClientCredential</span>(<span style="color: #2b91af">ConfigurationManager</span>.AppSettings[<span style="color: #a31515">"ClientId"</span>],
    <span style="color: #2b91af">ConfigurationManager</span>.AppSettings[<span style="color: #a31515">"ClientSecret"</span>]);
    <span style="color: #2b91af">AuthenticationResult</span> result = <span style="color: blue">await</span> authContext.AcquireTokenAsync(resource, clientCred);
 
    <span style="color: blue">if</span> (result == <span style="color: blue">null</span>)
        <span style="color: blue">throw</span> <span style="color: blue">new</span> <span style="color: #2b91af">InvalidOperationException</span>(<span style="color: #a31515">"Failed to obtain the JWT token"</span>);
 
    <span style="color: blue">return</span> result.AccessToken;
 
}
 
<span style="color: blue">private</span> <span style="color: blue">static</span> <span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: #2b91af">SecretItem</span>&gt; FetchKeyVaultSecrets(<span style="color: blue">string</span> vaultName)
{
 
    <span style="color: blue">try</span>
    {
 
        keyVaultClient = <span style="color: blue">new</span> <span style="color: #2b91af">KeyVaultClient</span>(<span style="color: blue">new</span> <span style="color: #2b91af">KeyVaultClient</span>.<span style="color: #2b91af">AuthenticationCallback</span>(GetToken));
        <span style="color: blue">var</span> secrets = keyVaultClient.GetSecretsAsync(<span style="color: #a31515">"https://"</span> + vaultName + <span style="color: #a31515">".vault.azure.net:443"</span>).Result.Value;
        <span style="color: blue">return</span> secrets;
 
    }
    <span style="color: blue">catch</span> (<span style="color: #2b91af">Exception</span> ex)
    {
 
        <span style="color: blue">return</span> <span style="color: blue">null</span>;
 
    }
 
}
 
<span style="color: blue">private</span> <span style="color: blue">static</span> <span style="color: blue">async</span> <span style="color: blue">void</span> ConnectToServices()
{
 
    <span style="color: blue">var</span> secrets = FetchKeyVaultSecrets(<span style="color: #a31515">"RohitMinni"</span>); <span style="color: green">//Fetch Secrets from the Vault</span>
    <span style="color: blue">var</span> certificate = <span style="color: blue">await</span> FetchKeyVaultCredential(secrets, <span style="color: #a31515">"certificate"</span>) <span style="color: blue">as</span> <span style="color: #2b91af">X509Certificate2</span>; <span style="color: green">//Gets the uploaded certificate from the vault with password if any</span>
    <span style="color: blue">var</span> subscriptionId = <span style="color: blue">await</span> FetchKeyVaultCredential(secrets, <span style="color: #a31515">"subscriptionid"</span>) <span style="color: blue">as</span> <span style="color: blue">string</span>;
    <span style="color: blue">var</span> cloudServices = <span style="color: blue">await</span> GetCloudService(subscriptionId, certificate);
 
    <span style="color: green">/*
 
    var o365Username = await FetchKeyVaultCredential(secrets, "o365username") as string;
    var o365Password = await FetchKeyVaultCredential(secrets, "o365password") as string;
 
    You can write custom code here to authenticate using this username and password
 
    */</span>
 
}
 
<span style="color: blue">public</span> <span style="color: blue">async</span> <span style="color: blue">static</span> <span style="color: #2b91af">Task</span>&lt;<span style="color: #2b91af">List</span>&lt;<span style="color: blue">string</span>&gt;&gt; GetCloudService(<span style="color: blue">string</span> subscriptionId, <span style="color: #2b91af">X509Certificate2</span> certificate)
{
 
    <span style="color: #2b91af">HostedServiceListResponse</span> response;
    <span style="color: #2b91af">List</span>&lt;<span style="color: blue">string</span>&gt; cloudServices;
    <span style="color: blue">try</span>
    {
 
        Microsoft.WindowsAzure.<span style="color: #2b91af">SubscriptionCloudCredentials</span> credential = <span style="color: blue">new</span> Microsoft.WindowsAzure.<span style="color: #2b91af">CertificateCloudCredentials</span>(subscriptionId, certificate);
        <span style="color: blue">using</span> (<span style="color: blue">var</span> computeClient = <span style="color: blue">new</span> <span style="color: #2b91af">ComputeManagementClient</span>(credential))
        {
 
            response = <span style="color: blue">await</span> computeClient.HostedServices.ListAsync();
            cloudServices = response.HostedServices.Select(s =&gt; s.ServiceName).ToList();
 
        }
        <span style="color: blue">return</span> cloudServices;
 
    }
    <span style="color: blue">catch</span> (<span style="color: #2b91af">Exception</span> ex)
    {
 
        <span style="color: blue">return</span> <span style="color: blue">null</span>;
 
    }
 
}

 private static async Task&lt;Object&gt; FetchKeyVaultCredential(IEnumerable&lt;SecretItem&gt; secrets, string secretType)
 {
 try
 {
 Secret localSecret = null;
 var secretId = secrets.Where(a =&gt; a.Identifier.Name.Contains(secretType)).FirstOrDefault();
 string certificatePassword = "";
 if (secretType == "certificate")
 {
 localSecret = await keyVaultClient.GetSecretAsync(secretId.Identifier.Identifier);
 var Password = localSecret.Value;

 //Extract associated certificate password if any
 var secretPasswordId = secrets.Where(a =&gt; a.Identifier.Name.Contains("certificatepassword")).FirstOrDefault();
 if(secretPasswordId != null)
 {
 localSecret = await keyVaultClient.GetSecretAsync(secretPasswordId.Identifier.Identifier); 
 certificatePassword = localSecret.Value;
 }
 var certificate = new X509Certificate2(Convert.FromBase64String(Password), certificatePassword, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
 return certificate;
 }
 else if(secretType == "subscriptionid")
 {
 localSecret = await keyVaultClient.GetSecretAsync(secretId.Identifier.Identifier);
 var Password = localSecret.Value;
 return Password;
 }
 else if (secretType == "subscriptionname")
 {
 localSecret = await keyVaultClient.GetSecretAsync(secretId.Identifier.Identifier);
 var Password = localSecret.Value;
 return Password;
 }
 }
 catch(Exception ex)
 {
 return null;
 }
 return null;
 }</pre>]]></content:encoded>
    </item>
    <item>
      <title>Encryption using Azure Key Vault - C# and PowerShell</title>
      <link>https://docs.microsoft.com/archive/blogs/rohit-minni/encryption-using-azure-key-vault-c-and-powershell</link>
      <pubDate>Sun, 01 Jan 2017 12:51:50 GMT</pubDate>
      <dc:creator><![CDATA[Rohit Minni]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.technet.microsoft.com/rohit-minni/?p=65</guid>
      <description><![CDATA[In this post I am going to show how you can encrypt strings using Azure Key Vault. Please refer...]]></description>
      <content:encoded><![CDATA[In this post I am going to show how you can encrypt strings using Azure Key Vault. Please refer <a href="https://docs.microsoft.com/en-us/rest/api/keyvault/about-keys--secrets-and-certificates#BKMK_Standards">this</a> documentation for the encryption standards followed by Azure Key Vault. So, lets start by creating a new Key Vault in Azure. Once you have done that, generate a new Key which is a Software Key and name it as "NewKey".

The below C# class code will then be able to encrypt and decrypt strings using the Azure Key Vault. It uses Service Principal to access the key vault, so make sure your vault is accessible by the Service Principal you use to authenticate.

<pre style="font-family:Consolas;font-size:13;color:black;background:white"><span style="color:blue">public</span>&nbsp;<span style="color:blue">class</span>&nbsp;<span style="color:#2b91af">KeyVaultDecryptor</span>
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">private</span>&nbsp;<span style="color:blue">string</span>&nbsp;vaultAddress;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">private</span>&nbsp;<span style="color:blue">string</span>&nbsp;clientId;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">private</span>&nbsp;<span style="color:blue">string</span>&nbsp;clientSecret;
 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">public</span>&nbsp;KeyVaultDecryptor(<span style="color:blue">string</span>&nbsp;vaultAddress,&nbsp;<span style="color:blue">string</span>&nbsp;clientId,&nbsp;<span style="color:blue">string</span>&nbsp;clientSecret)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">this</span>.vaultAddress&nbsp;=&nbsp;vaultAddress;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">this</span>.clientId&nbsp;=&nbsp;clientId;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">this</span>.clientSecret&nbsp;=&nbsp;clientSecret;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">public</span>&nbsp;<span style="color:blue">string</span>&nbsp;DecryptText(<span style="color:blue">string</span>&nbsp;textToDecrypt)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">var</span>&nbsp;kv&nbsp;=&nbsp;<span style="color:blue">new</span>&nbsp;<span style="color:#2b91af">KeyVaultClient</span>(<span style="color:blue">new</span>&nbsp;<span style="color:#2b91af">KeyVaultClient</span>.<span style="color:#2b91af">AuthenticationCallback</span>(GetToken));
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">try</span>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">var</span>&nbsp;key&nbsp;=&nbsp;kv.GetKeyAsync(vaultAddress,&nbsp;<span style="color:#a31515">&quot;NewKey&quot;</span>,&nbsp;<span style="color:blue">null</span>).GetAwaiter().GetResult();
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">var</span>&nbsp;publicKey&nbsp;=&nbsp;<span style="color:#2b91af">Convert</span>.ToBase64String(key.Key.N);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">using</span>&nbsp;(<span style="color:blue">var</span>&nbsp;rsa&nbsp;=&nbsp;<span style="color:blue">new</span>&nbsp;<span style="color:#2b91af">RSACryptoServiceProvider</span>())
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">var</span>&nbsp;p&nbsp;=&nbsp;<span style="color:blue">new</span>&nbsp;<span style="color:#2b91af">RSAParameters</span>()&nbsp;{&nbsp;Modulus&nbsp;=&nbsp;key.Key.N,&nbsp;Exponent&nbsp;=&nbsp;key.Key.E&nbsp;};
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;rsa.ImportParameters(p);
 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green">//&nbsp;Decrypt</span>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">var</span>&nbsp;encryptedTextNew&nbsp;=&nbsp;<span style="color:#2b91af">Convert</span>.FromBase64String(textToDecrypt);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">var</span>&nbsp;decryptedData&nbsp;=&nbsp;kv.DecryptDataAsync(key.Key,&nbsp;<span style="color:#2b91af">JsonWebKeyEncryptionAlgorithm</span>.RSAOAEP,&nbsp;encryptedTextNew).GetAwaiter().GetResult();
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">var</span>&nbsp;decryptedText&nbsp;=&nbsp;<span style="color:#2b91af">Encoding</span>.Unicode.GetString(decryptedData.Result);
 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">return</span>&nbsp;decryptedText;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">catch</span>&nbsp;(<span style="color:#2b91af">Exception</span>&nbsp;ex)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">return</span>&nbsp;<span style="color:#a31515">&quot;&quot;</span>;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">public</span>&nbsp;<span style="color:blue">string</span>&nbsp;EncryptText(<span style="color:blue">string</span>&nbsp;textToEncrypt)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">var</span>&nbsp;kv&nbsp;=&nbsp;<span style="color:blue">new</span>&nbsp;<span style="color:#2b91af">KeyVaultClient</span>(<span style="color:blue">new</span>&nbsp;<span style="color:#2b91af">KeyVaultClient</span>.<span style="color:#2b91af">AuthenticationCallback</span>(GetToken));
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">try</span>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">var</span>&nbsp;key&nbsp;=&nbsp;kv.GetKeyAsync(vaultAddress,&nbsp;<span style="color:#a31515">&quot;NewKey&quot;</span>,&nbsp;<span style="color:blue">null</span>).GetAwaiter().GetResult();
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">var</span>&nbsp;publicKey&nbsp;=&nbsp;<span style="color:#2b91af">Convert</span>.ToBase64String(key.Key.N);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">using</span>&nbsp;(<span style="color:blue">var</span>&nbsp;rsa&nbsp;=&nbsp;<span style="color:blue">new</span>&nbsp;<span style="color:#2b91af">RSACryptoServiceProvider</span>())
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">var</span>&nbsp;p&nbsp;=&nbsp;<span style="color:blue">new</span>&nbsp;<span style="color:#2b91af">RSAParameters</span>()&nbsp;{&nbsp;Modulus&nbsp;=&nbsp;key.Key.N,&nbsp;Exponent&nbsp;=&nbsp;key.Key.E&nbsp;};
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;rsa.ImportParameters(p);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">var</span>&nbsp;byteData&nbsp;=&nbsp;<span style="color:#2b91af">Encoding</span>.Unicode.GetBytes(textToEncrypt);
 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green">//&nbsp;Encrypt</span>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">var</span>&nbsp;encryptedText&nbsp;=&nbsp;rsa.Encrypt(byteData,&nbsp;<span style="color:blue">true</span>);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">string</span>&nbsp;encText&nbsp;=&nbsp;<span style="color:#2b91af">Convert</span>.ToBase64String(encryptedText);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">return</span>&nbsp;encText;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">catch</span>&nbsp;(<span style="color:#2b91af">Exception</span>&nbsp;ex)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">return</span>&nbsp;<span style="color:#a31515">&quot;&quot;</span>;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">async</span>&nbsp;<span style="color:#2b91af">Task</span>&lt;<span style="color:blue">string</span>&gt;&nbsp;GetToken(<span style="color:blue">string</span>&nbsp;authorization,&nbsp;<span style="color:blue">string</span>&nbsp;resource,&nbsp;<span style="color:blue">string</span>&nbsp;scope)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">var</span>&nbsp;authContext&nbsp;=&nbsp;<span style="color:blue">new</span>&nbsp;<span style="color:#2b91af">AuthenticationContext</span>(authorization);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af">ClientCredential</span>&nbsp;clientCred&nbsp;=&nbsp;<span style="color:blue">new</span>&nbsp;<span style="color:#2b91af">ClientCredential</span>(clientId,clientSecret);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af">AuthenticationResult</span>&nbsp;result&nbsp;=&nbsp;<span style="color:blue">await</span>&nbsp;authContext.AcquireTokenAsync(resource,&nbsp;clientCred);
 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">if</span>&nbsp;(result&nbsp;==&nbsp;<span style="color:blue">null</span>)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">throw</span>&nbsp;<span style="color:blue">new</span>&nbsp;<span style="color:#2b91af">InvalidOperationException</span>(<span style="color:#a31515">&quot;Failed&nbsp;to&nbsp;obtain&nbsp;the&nbsp;JWT&nbsp;token&quot;</span>);
 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue">return</span>&nbsp;result.AccessToken;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;}</pre>

You can refer to my other blog <a href="https://blogs.technet.microsoft.com/rohit-minni/2016/12/31/convert-a-code-in-c-to-be-used-in-powershell/">here</a> to convert this C# code to PowerShell or use the attached zipped module directly in PowerShell or Azure Automation - <a href="https://msdnshared.blob.core.windows.net/media/2017/01/KeyVaultDecryptor.zip">keyvaultdecryptor</a>

A sample PowerShell code to use Key Vault Encryption in Azure Automation:

<code>[System.Reflection.Assembly]::LoadFrom("C:\Modules\User\KeyVaultDecryptor\KeyVaultDecryptor.dll") | Out-Null ##For Azure Automation that is the path where modules get uploaded</code>

<code>$VaultAddress="https://****.vault.azure.net"</code>

<code>$ClientId="99b*****************1cb91d"</code>

<code>$ClientSecret="Cjl*****************yfTJes0U="</code>

<code>$KeyVaultClient = New-Object KeyVaultDecryptor.KeyVaultDecryptor -argumentlist $VaultAddress, $ClientId, $ClientSecret</code>

<code>$encrypt = $KeyVaultClient.EncryptText("Administrator@123")</code>

<code>$decrypt = $KeyVaultClient.DecryptText($encrypt)</code>]]></content:encoded>
    </item>
    <item>
      <title>Convert a code in C# to be used in PowerShell</title>
      <link>https://docs.microsoft.com/archive/blogs/rohit-minni/convert-a-code-in-c-to-be-used-in-powershell</link>
      <pubDate>Sat, 31 Dec 2016 11:59:33 GMT</pubDate>
      <dc:creator><![CDATA[Rohit Minni]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.technet.microsoft.com/rohit-minni/?p=25</guid>
      <description><![CDATA[Have a piece of code working in C# and want to use the same in PowerShell? Well, no problem!

Open...]]></description>
      <content:encoded><![CDATA[Have a piece of code working in C# and want to use the same in PowerShell? Well, no problem!

Open Visual Studio, create a class library, compile it and when you reference your dll in PowerShell - you're all set. So, lets see how we can do this step by step.
<ol>
 	<li>Open Visual Studio and create a new solution/project - Make sure you select the type as Class Library<img src="https://msdnshared.blob.core.windows.net/media/2016/12/img1.png" width="727" height="503" class="alignnone wp-image-35 " /></li>
 	<li>For this example, I have renamed the class to TestLibrary and defined two functions as follows:</li>
 	<li><code>public string SayHello()</code>
<code> {</code>
<code> return "Hello World";</code>
<code> }</code>
<code> public string Echo(string value)</code>
<code> {</code>
<code> return value;</code>
<code> }</code></li>
 	<li>Please note that at this point, you might also want to add any Nuget packages to your code in case you are referring to them in your code.</li>
 	<li>Rebuild your solution to make sure everything is good and you have the binaries generated.</li>
 	<li>Now browse to your project folder which would have a similar folder path: ...\visual studio 2015\Projects\ConvertCodeForPS\ConvertCodeForPS\bin\Debug</li>
 	<li>Copy the contents of this folder and paste them in a new folder called <span><span>ConvertCodeForPS</span></span>
<img src="https://msdnshared.blob.core.windows.net/media/2016/12/img2.png" width="668" height="143" class="alignnone wp-image-16 " /></li>
 	<li>Now, copy this folder into one of the PSModulePath defined folders like C:\Program Files (x86)\WindowsPowerShell\Modules<img src="https://msdnshared.blob.core.windows.net/media/2016/12/img3-1024x116.png" alt="img3" width="786" height="89" class="alignnone wp-image-45" /></li>
 	<li>Open your PowerShell ISE now and load the module you just created:[System.Reflection.Assembly]::LoadFrom("C:\Program Files (x86)\WindowsPowerShell\Modules\ConvertCodeForPS\ConvertCodeForPS.dll")<img src="https://msdnshared.blob.core.windows.net/media/2016/12/img4.png" alt="img4" width="1080" height="234" class="alignnone size-full wp-image-55" /></li>
 	<li>We have then instantiated our class and called the respective functions we created in our tutorial.</li>
</ol>
&nbsp;

Cheers :)

&nbsp;]]></content:encoded>
    </item>
  </channel>
</rss>