Encode in C# and Decode in PowerShell


 

I had a requirement to read some data in C# windows application, store it in database  and then later use it in a PowerShell script.

It was also required that some data like ‘Keys’ should not be saved directly in database i.e. should not be visible directly to other database users.

One approach is to use complex encryption decryption logic when high data security is a requirement. Read more about Encryption and Decryption of Data here.

Another approach is to use Base64 encoding and decoding approach where very high data security is not a requirement. More about Base64 encoding here and decoding here.

I opted out for Base64 encoding approach as data was not getting shared with external sources where data security is very important and my applications and database were in the same network.

Here comes the coding blog 🙂 !!!

1. Encode in C# :-

   1: public string EncodeKey(string txtKey)
   2: {
   3:     byte[] passBytes = System.Text.Encoding.Unicode.GetBytes(txtKey);
   4:     string encodedKey = Convert.ToBase64String(passBytes);
   5:     return encodedKey;
   6: }

2. Decode in PowerShell :-

   1: Function ReadData
   2: {
   3:     $ConnectionString = "Data Source='';Initial Catalog='';Integrated Security=SSPI;"
   4:     $con = New-Object "System.Data.SqlClient.SQLConnection"
   5:     $con.ConnectionString = $ConnectionString
   6:     $con.Open()
   7:  
   8:     $sqlcmd = New-Object "System.Data.SqlClient.SqlCommand"
   9:     $sqlcmd.connection = $con
  10:  
  11:     $sqlcmd.CommandText = “Select Key from MyDemoTable where KeyIndex = 'FirstKey'
  12:     $ds = New-Object System.Data.DataSet
  13:     $da = New-Object System.Data.SqlClient.SqlDataAdapter($sqlcmd)
  14:     $return = $da.fill($ds)
  15:     
  16:     $encodedKeyFromDb = $ds.Tables[0].Rows[0][0]
  17:     $originalKey = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($encodedKeyFromDb))
  18:  
  19:     ## Use the Key for Further Code ##
  20: }

Please note that Base64String encoding is very simple to reverse and do not involves any private or public key concept. In situations where data security is a requirement, Encryption Decryption approach should be followed.

Happy Coding!!!


Comments (1)

  1. MARK says:

    Thanks for valuable info.

Skip to main content