以下的示例演示了如何使用RSACryptoServiceProvider类加密一个字符串.ExportParameter(bool)方法根据参数的真假允许获得公钥/私钥对中的公钥.
using System.Security.Cryptography;
using System;
using System.Text;
namespace ConsoleApplication1
{
public class ExternTest
{
static void Main(string[] args)
{
//string sMsg = "The message to encrypt!";
//string sEnc, sDec;
//DESCryptoServiceProvider des = new DESCryptoServiceProvider();
//System.Text.Encoding utf = new System.Text.UTF8Encoding();
//byte[] key = utf.GetBytes("12345678");
//byte[] iv ={ 1, 2, 3, 4, 5, 6, 7, 8 };
//ICryptoTransform encryptor = des.CreateEncryptor(key, iv);
//ICryptoTransform descryptor = des.CreateDecryptor(key, iv);
//{
// byte[] bMsg = utf.GetBytes(sMsg);
// byte[] bEnc = encryptor.TransformFinalBlock(bMsg, 0, bMsg.Length);
// sEnc = System.Convert.ToBase64String(bEnc);
//}
//{
// byte[] bEnc = System.Convert.FromBase64String(sEnc);
// byte[] bDec = descryptor.TransformFinalBlock(bEnc, 0, bEnc.Length);
// sDec = utf.GetString(bDec);
//}
//Console.WriteLine("Message :" + sMsg);
//Console.WriteLine("Encrypted: " + sEnc);
//Console.WriteLine("Decrypted: " + sDec);
string sMsg = "The message to encrypt!";
string sEnc, sDec;
System.Text.Encoding utf = new System.Text.UTF8Encoding();
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
RSAParameters publicKey = rsa.ExportParameters(true);
RSAParameters publicAndPrivateKey = rsa.ExportParameters(true);
{
RSACryptoServiceProvider rsaEncrypor = new RSACryptoServiceProvider();
rsaEncrypor.ImportParameters(publicKey);
byte[] bMsg = utf.GetBytes(sMsg);
byte[] bEnc = rsaEncrypor.Encrypt(bMsg, false);
sEnc = System.Convert.ToBase64String(bEnc);
}
{
RSACryptoServiceProvider rsaDecryptor = new RSACryptoServiceProvider();
rsaDecryptor.ImportParameters(publicAndPrivateKey);
byte[] bEnc = System.Convert.FromBase64String(sEnc);
byte[] bDec = rsaDecryptor.Decrypt(bEnc, false);
sDec = utf.GetString(bDec);
}
System.Console.WriteLine("Message :" + sMsg);
Console.WriteLine("Encrypted:" + sEnc);
Console.WriteLine("Decrypted:" + sDec);
}
}
}