How can I use ConvertTo-SecureString

Question:

Let’s say I need to do this in Powershell:

The content of $CredPath is a file that contains the output of ConvertFrom-SecureString -Key (1..16).

How do I accomplish the ConvertTo-SecureString -key (1..16) portion in C#/.NET?

I know how to create a SecureString, but I’m not sure how the encryption should be handled.

Do I encrypt each character using AES, or decrypt the string and then create a the secure string per character?

I know next to nothing about cryptography, but from what I’ve gathered I might just want to invoke the Powershell command using C#.

For reference, I found a similar post about AES encryption/decryption here:
Using AES encryption in C#

UPDATE

I have reviewed the link Keith posted, but I face additional unknowns. The DecryptStringFromBytes_Aes takes three arguments:

The first argument is a byte array represents the encrypted text. The question here is, how should the string be represented in the byte array? Should it be represented with or without encoding?

The second byte array is the key should simply be an array of integers:

The third byte array is an “Initialization Vector” – it looks like the Aes.Create() call will generate a byte[] for IV randomly. Reading around, I’ve found that I might need to use the same IV. As ConvertFrom-SecureString and ConvertTo-SecureString are able to encrypt/decrypt using simply the key, I am left with the assumption that the IV[] can be random -or- has a static definition.

I have not yet found a winning combination, but I will keep trying.

Answer:

I know this is an old post. I am posting this for completeness and posterity, because I couldn’t find a complete answer on MSDN or stackoverflow. It will be here in case I ever need to do this again.

It is a C# implementation of of powershell’s ConvertTo-SecureString with AES encryption (turned on by using the -key option). I will leave it for exercise to code a C# implementation of ConvertFrom-SecureString.

My work is combining answers and re-arranging user2748365’s answer to be more readable and adding educational comments! I also fixed the issue with taking a substring — at the time of this post, his code only has two elements in strArray.

Source:

How can I use ConvertTo-SecureString by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply