Running csencrypt from within PowerShell RRS feed

  • Question

  • I have a situation where I will be taking a users password on the command line as they call a PS script I have. Inside of the script, I need to encrypt this value and then write it to a PS variable. I'll put this string in a config file.

    So, withing PS I can get the script to run like this:

    $appCmd = "&'C:\Program Files\Microsoft SDKs\Windows Azure\.NET SDK\2012-06\bin\csencrypt.exe'"
    $args = 'encrypt-password -Output mycopy.txt -Thumbprint "...EC7F4..."'

    Invoke-Expression "$appCmd $args" | Out-Host

    This code runs but then throws an error because csencrypt appears to be expecting a console window to appear so I can type in the password. As you see above, my initial attempt was to just write the encrypted output to a file but really I need it in a PS variable.

    It seems to me that I need to have csencrypt take the password as a parameter itself although it doesn't look like it works like this.

    Any ideas on how to get this to work in PowerShell?



    Friday, September 21, 2012 7:34 PM


All replies

  • According to http://msdn.microsoft.com/en-us/library/windowsazure/hh404001.aspx,
    if input to CSEncrypt is redirected from stdin, CSEncrypt reads one line of
    input and encrypts the result. So try to add a line beneath the command.
    Thursday, September 27, 2012 1:22 PM
  • It's simple enough to convert a clear text password into the required token directly in PowerShell:

    $null = [System.Reflection.Assembly]::LoadWithPartialName("System.Security")
    function EncryptString($clearText, $certificate)
        $ci = [Security.Cryptography.Pkcs.ContentInfo]::New( [Text.Encoding]::UTF8.GetBytes($clearText) )
        $enveloped = [Security.Cryptography.Pkcs.EnvelopedCms]::new($ci)
        $encryptedBase64 = [Convert]::ToBase64String($enveloped.Encode())
    function DecryptBase64($EncryptedBase64)
        $decryptEnvelope = [Security.Cryptography.Pkcs.EnvelopedCms]::new()
        $decryptedString = [Text.Encoding]::UTF8.GetString($decryptEnvelope.ContentInfo.Content)
    $password = '*PASSWORD*'
    $certificateThumbprint = '0000000000000000000000000000000000000000'
    $certificate = Get-Item "cert:\LocalMachine\My\$certificateThumbprint"
    $encryptedPassword = EncryptString $password $certificate
    $decryptedPassword = DecryptBase64 $encryptedPassword
    # Test decrypt matches original.
    if ($decryptedPassword -eq $password)
    } else {
        'Failed, decrypted password does not match original password'

    Thursday, June 23, 2016 3:01 AM