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)
3: byte passBytes = System.Text.Encoding.Unicode.GetBytes(txtKey);
4: string encodedKey = Convert.ToBase64String(passBytes);
5: return encodedKey;
2. Decode in PowerShell :-
1: Function ReadData
3: $ConnectionString = "Data Source='';Initial Catalog='';Integrated Security=SSPI;"
4: $con = New-Object "System.Data.SqlClient.SQLConnection"
5: $con.ConnectionString = $ConnectionString
8: $sqlcmd = New-Object "System.Data.SqlClient.SqlCommand"
9: $sqlcmd.connection = $con
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)
16: $encodedKeyFromDb = $ds.Tables.Rows
17: $originalKey = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($encodedKeyFromDb))
19: ## Use the Key for Further Code ##
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.