/**//* 基于RSA的數字簽名和驗證C#源碼
* (采用字元串作為參數)RSA_Demo3
*
* 夏春濤 Email:[email protected]
* Blog:http://bluesky521.cnblogs.com
* 運作環境:.net2.0 framework
*/
/**//* 備注:
* 若要使用公鑰系統對消息進行數字簽名,發送方先向該消息應用哈希函數以建立消息摘要。
* 然後,發送方用自己的私鑰對消息摘要進行加密,以建立發送方的個人簽名。在收到消息和
* 簽名後,接收方使用發送方的公鑰解密該簽名,以恢複消息摘要,并使用發送方所用的同一
* 雜湊演算法對該消息進行哈希運算。如果接收方計算的消息摘要與從發送方收到的消息摘要完
* 全比對,則接收方可以假定消息在傳輸中未被更改。請注意,因為發送方的公鑰是公共知識,
* 是以任何人都可以驗證簽名。
using System;
using System.Security.Cryptography;
using System.Text;
class RSACSPSample
{
static void Main()
try
string str_DataToSign = @"Data to Sign!Data to Sign!Data to Sign!";
Console.WriteLine("原文:" + str_DataToSign);
Console.WriteLine("長度:" + str_DataToSign.Length.ToString());
Console.WriteLine();
RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider();
string str_Private_Key = Convert.ToBase64String( RSAalg.ExportCspBlob(true) );
string str_Public_Key = Convert.ToBase64String( RSAalg.ExportCspBlob(false) );
Console.WriteLine("公鑰:" + str_Public_Key);
Console.WriteLine("私鑰:" + str_Private_Key);
string str_SignedData = HashAndSign(str_DataToSign, str_Private_Key);// Hash and sign the data.
Console.WriteLine("簽名資料:" + str_SignedData);
if (VerifySignedHash(str_DataToSign, str_SignedData, str_Public_Key))
Console.WriteLine("驗證簽名OK.");
}
else
Console.WriteLine("簽名不比對!");
}
catch (ArgumentNullException)
Console.WriteLine("The data was not signed or verified");
}
//對資料簽名
public static string HashAndSign(string str_DataToSign, string str_Private_Key)
ASCIIEncoding ByteConverter = new ASCIIEncoding();
byte[] DataToSign = ByteConverter.GetBytes(str_DataToSign);
RSAalg.ImportCspBlob( Convert.FromBase64String(str_Private_Key) );
byte[] signedData = RSAalg.SignData(DataToSign, new SHA1CryptoServiceProvider());
string str_SignedData = Convert.ToBase64String(signedData);
return str_SignedData;
catch (CryptographicException e)
Console.WriteLine(e.Message);
return null;
//驗證簽名
public static bool VerifySignedHash(string str_DataToVerify, string str_SignedData, string str_Public_Key)
byte[] SignedData = Convert.FromBase64String(str_SignedData);
byte[] DataToVerify = ByteConverter.GetBytes(str_DataToVerify);
RSAalg.ImportCspBlob( Convert.FromBase64String(str_Public_Key) );
return RSAalg.VerifyData(DataToVerify, new SHA1CryptoServiceProvider(), SignedData);
return false;
}