RSA (for Windows)
RSA is an asymmetric encyption algorithm, which uses two keys, one to encrypt and the other
to decrypt. It was created in 1977 by Ron Rivest, Adi Shamir, and Leonard Adleman, and is still one of the most widely used encryption methods. A typical application is in authenticating a sender, where the senders private key is used to encrypt a message, and then is decrypted by the receiver with the senders public key (which is known to anyone who wants it). It is also typically used for encrypting disks/files, such as for EFS.
As much as possible ASP.NET is used on these pages to make it Web-based.
Unfortunately the Web-based version does not run, as there can be security
problems. Thus this page gives the code for a Windows version.
For a Windows EXE: [Click here]
A sample run is:
The code is:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
namespace rsa
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
RSAParameters publickey = rsa.ExportParameters(false); // don't export private key
RSAParameters privatekey = rsa.ExportParameters(true); // export private key
this.tbPublicKey.Text = "e=" + ByteToString(publickey.Exponent) + ", n=" + ByteToString(publickey.Modulus);
this.tbPrivateKey.Text = "d=" + ByteToString(privatekey.D) + ", n=" + ByteToString(publickey.Modulus);
rsa.ImportParameters(publickey);
byte[] encryptedData = rsa.Encrypt(StringToByte(this.tbMessage.Text), true);
this.tbEncrypt.Text = ByteToString(encryptedData);
rsa.ImportParameters(privatekey);
byte[] decryptedData = rsa.Decrypt(encryptedData, true);
this.tbDecrypt.Text = ByteToString2(decryptedData);
}
catch (Exception ex)
{
this.tbEncrypt.Text = ex.Message.ToString();
}
}
public static byte[] StringToByte(string StringToConvert)
{
char[] CharArray = StringToConvert.ToCharArray();
byte[] ByteArray = new byte[CharArray.Length];
for (int i = 0; i < CharArray.Length; i++)
{
ByteArray[i] = Convert.ToByte(CharArray[i]);
}
return ByteArray;
}
public static string ByteToString(CryptoStream buff)
{
string sbinary = "";
int b = 0;
do
{
b = buff.ReadByte();
if (b != -1) sbinary += ((char)b);
} while (b != -1);
return (sbinary);
}
public static string ByteToString(byte[] buff)
{
string sbinary = "";
for (int i = 0; i < buff.Length; i++)
{
sbinary += buff[i].ToString("X2"); // hex format
}
return (sbinary);
}
public static string ByteToString2(byte[] buff)
{
string sbinary = "";
for (int i = 0; i < buff.Length; i++)
{
sbinary += (char)buff[i]; // hex format
}
return (sbinary);
}
}
}
|