110,499
社区成员
发帖
与我相关
我的任务
分享
public partial class FormRsaEncrypt : Form
{
public FormRsaEncrypt()
{
InitializeComponent();
this.Text = "RSA 加密解密";
textBoxEncrypt.ReadOnly = true;
textBoxDecrypt.ReadOnly = true;
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
this.txbPrivateKey.Text = RSA.ToXmlString(true);
this.txbPublicKey.Text = RSA.ToXmlString(false);
RSA.Clear();
}
private void buttonOK_Click(object sender, EventArgs e)
{
//int TextLength = 128;
byte[] encryptedData;
byte[] decryptedData;
try
{
RSACryptoServiceProvider RSA1 = new RSACryptoServiceProvider();
RSA1.FromXmlString(this.txbPrivateKey.Text);
RSAParameters RSAKeyInfo = RSA1.ExportParameters(true);
//byte[] dataToEncrypt = GenerateBytes(TextLength);
byte[] dataToEncrypt = Encoding.UTF8.GetBytes(this.textBoxInput.Text);
encryptedData = RSAEncrypt(dataToEncrypt, RSAKeyInfo.Exponent, RSAKeyInfo.Modulus);
int x = encryptedData.Length;
this.textBoxEncrypt.Text = Convert.ToBase64String(encryptedData);
decryptedData = RSADecrypt(encryptedData, RSAKeyInfo.D, RSAKeyInfo.Modulus);
int y = decryptedData.Length;
this.textBoxDecrypt.Text = Convert.ToBase64String(decryptedData);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//***********************************************************************
// RSA Encrypt
//***********************************************************************
static public byte[] RSAEncrypt(byte[] dataToEncrypt, byte[] Exponent, byte[] Modulus)
{
BigInteger original = new BigInteger(dataToEncrypt);
BigInteger e = new BigInteger(Exponent);
BigInteger n = new BigInteger(Modulus);
BigInteger encrypted = BigInteger.ModPow(original, e, n);
return encrypted.ToByteArray();
}
//***********************************************************************
// RSA Decrypt
//***********************************************************************
static public byte[] RSADecrypt(byte[] encryptedData, byte[] D, byte[] Modulus)
{
BigInteger encrypted = new BigInteger(encryptedData);
BigInteger d = new BigInteger(D);
BigInteger n = new BigInteger(Modulus);
BigInteger decrypted = BigInteger.ModPow(encrypted, d, n);
return decrypted.ToByteArray();
}
}
//Pass the data to ENCRYPT, the public key information
//(using RSACryptoServiceProvider.ExportParameters(false),
//and a boolean flag specifying no OAEP padding.
encryptedData = RSAEncrypt(dataToEncrypt, RSA.ExportParameters(false), false);
//Pass the data to DECRYPT, the private key information
//(using RSACryptoServiceProvider.ExportParameters(true),
//and a boolean flag specifying no OAEP padding.
decryptedData = RSADecrypt(encryptedData, RSA.ExportParameters(true), false);