Creating a Public and Private Key using C#
May 4, 2012 Leave a comment
Requirements:
- Folder named “Keys”
- New Class named “PrivatePublicKey.cs”
- An ASPX page with any name
Class PrivatePublicKey Imports
using System.IO;
using System.Security.Cryptography;
Class PrivatePublicKey Methods
public void CreateKeyPairs(string publicprivatepath, string publicpath)
{
FileStream filekeypair = new FileStream(publicprivatepath, FileMode.Create);
FileStream filepublickey = new FileStream(publicpath, FileMode.Create);
StreamWriter sw = new StreamWriter(filekeypair);
StreamWriter sw2 = new StreamWriter(filepublickey);
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
string publicPrivateKeyXML = rsa.ToXmlString(true);
sw.Write(publicPrivateKeyXML);
sw.Close();
string publicOnlyKeyXML = rsa.ToXmlString(false);
sw2.Write(publicOnlyKeyXML);
sw2.Close();
}
ASPX Page
Create a new Folder named “Keys”
Create a new ASPX page and name as wished
Add an input field such as: <asp:TextBox ID=”txt_username” runat=”server”></asp:TextBox>
Insert the following code where desired, preferably on Register Click Button Event:
string Username = txt_username.Text;
PrivatePublicKey pp = new PrivatePublicKey();
string keyPair = “../Keys/” + Username + “pair.xml”; //Creating an XML file with both the Private and Public Key
string keyPublic = “../Keys/” + Username + “public.xml”; //Creating an XML file with only the Public Key to be shared
pp.CreateKeyPairs(Server.MapPath(keyPair), Server.MapPath(keyPublic));







