Cryptography


Cryptography

The code snippet demonstrates how to use cryptography concepts using public key and private key.

The text is converted into cyphertext with the use of public key. The original text is restored using the private key.

Namespaces to be used are:

using System.Security.Cryptography;




namespace WindowsFormsApplication12
{
public partial class Form12 : Form
{ public string xmlpublickey,xmlprivatekey;
byte[] plaintextarray;
byte[] cypertextarray;

public Form12()
{
InitializeComponent();
}

private void Form12_Load(object sender, EventArgs e)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
xmlprivatekey = rsa.ToXmlString(true );
xmlpublickey = rsa.ToXmlString(false );

}

private void button1_Click(object sender, EventArgs e)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(xmlpublickey);
string msg = textBox1.Text;
plaintextarray = (new UnicodeEncoding()).GetBytes(msg);
cypertextarray = rsa.Encrypt(plaintextarray, false);

for (int i = 0; i < cypertextarray.Length ; i++)
{
textBox2.Text += (char)cypertextarray[i];
}

}

private void button2_Click(object sender, EventArgs e)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(xmlprivatekey);
byte[] originaltext = rsa.Decrypt(cypertextarray, false);

for (int i = 0; i < originaltext.Length; i++)
{
textBox3.Text += (char)originaltext[i];
}

}
}
}



Explanation:

The above snippet uses the public key to encrypt the data and private key to decrypt.

Encryption:

The text is converted to bytearray and public key is applied on it .The output is encrypted data.

Decryption:

The encrypted data in combination with private key restores the original text.


Defining of public and private keys:

xmlprivatekey = rsa.ToXmlString(true );
xmlpublickey = rsa.ToXmlString(false );


encryption :

cypertextarray = rsa.Encrypt(plaintextarray, false);

decryption :

byte[] originaltext = rsa.Decrypt(cypertextarray, false);


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: