asymmetric encryption for text field
I am trying to understanding and I have been looking at examples after
examples and from what I read so far I will try to explain my plan to make
sure I am headed in the right direction.
When the user saves the form my plan is to encrypt the data using
asymmetric encryption which has a separate public key and a private key(I
know there is a performance decrease using this option and I am okay with
that)So the data to be encrypted will never get decrypted again on the
site available to the public.
My plan is to have another website located on the inside of our network
with no access to the outside to then read this information and decrypt
the data. I am able to encrypt the data using this method but not really
understanding how to save the key to use for decrypt in another website.
My overall confusion is what to do with the Keys and how to work with them
later.
Would i save the "privateKeyAsXml" to a table in the database? And will
that require a separate record for each key saved or is there a way to
generate a static key to encrypt and one to decrypt all data? Then will I
also have to save the public key in the table also to have some way to
link the 2 keys?
Below is my example of how I am encrypting the data but not sure how to
decrypt data by calling the saved key if it is in another location. The
examples I have tried all encrypt and decrypt in the same file to get you
familiar with how it works.
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "storedprocedure";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@currentuser",
SqlDbType.VarChar, 30));
cmd.Parameters["@currentuser"].Value = Session["mysession"];
UTF8Encoding encoding = new UTF8Encoding();
string text = Request.Form["textbox3"];
byte[] textAsBytes = encoding.GetBytes(text);
RSACryptoServiceProvider rsa = new
RSACryptoServiceProvider(1024);
//Export the keys as XML
string publicKeyAsXml = rsa.ToXmlString(false);
****SHOULD I SAVE THE PRIVATEKEY TO A DATABASE
string privateKeyAsXml = rsa.ToXmlString(true);
//Create a new instance of the RSACryptoServiceProvider
//and load the public key parameters so it can be used
//to encrypt
RSACryptoServiceProvider publicKeyRSA = new
RSACryptoServiceProvider(1024);
publicKeyRSA.FromXmlString(publicKeyAsXml);
byte[] encryptedData = publicKeyRSA.Encrypt(textAsBytes,
true);
cmd.Parameters.AddWithValue("@parametervalue",
encryptedData);
This is the code I have to decrypt but not sure how I would read the
encrypted data from sql and then load the private key from another source
to then decrypt the data?
RSACryptoServiceProvider privateKeyRSA = new RSACryptoServiceProvider();
privateKeyRSA.FromXmlString(privateKeyAsXml);
byte[] unencryptedBytes =
privateKeyRSA.Decrypt(encryptedData, true);
No comments:
Post a Comment