偶寫的最簡單的數字簽名核心代碼

    //準備存儲加密後的值
   byte[]  SignedHashValue;

   RSACryptoServiceProvider rsa=new RSACryptoServiceProvider();
   RSAPKCS1SignatureFormatter rsaFormatter=new RSAPKCS1SignatureFormatter(rsa);
   rsaFormatter.SetHashAlgorithm("SHA1");
   //導出公鑰和私鑰
   myPublic=rsa.ExportParameters(true);
   myPrivate=rsa.ExportParameters(true);
   //執行生成數字簽名
   SignedHashValue=rsaFormatter.CreateSignature(HashValue);

 

   //創建新的RSA對象
   RSACryptoServiceProvider RSA2 = new RSACryptoServiceProvider();
   //導入發佈的公鑰
   RSAParameters rasKeyInfo=new RSAParameters();
   rasKeyInfo.Modulus = myPublic.Modulus;
   rasKeyInfo.Exponent = myPublic.Exponent;
   RSA2.ImportParameters(rasKeyInfo);
   //使用公鑰進行解密
   RSAPKCS1SignatureDeformatter RSADeformatter = new RSAPKCS1SignatureDeformatter(RSA2);
   //指定原加密算法
   RSADeformatter.SetHashAlgorithm("SHA1");
   //進行比較 判斷簽名是否有效
   if(RSADeformatter.VerifySignature(HashValue, SignedHashValue))
   {
    Response.Write("經過驗證改簽名有效");
   }
   else
   {
    Response.Write("經過驗證改簽名無效");
   }

上面這個是 先用自己的私鑰加密後發送給對方 對方使用公鑰進行解密

 

下面這個是  對方向我發文件 先用公鑰加密後發送給我 我使用私鑰進行解密 完成數字簽名的校驗

轉載自由 LVLV

 RSACryptoServiceProvider rsa=new RSACryptoServiceProvider();
   RSAPKCS1SignatureFormatter rsaFormatter=new RSAPKCS1SignatureFormatter(rsa);
   rsaFormatter.SetHashAlgorithm("SHA1");
   //導出公鑰和私鑰
   myPublic=rsa.ExportParameters(false);
   myPrivate=rsa.ExportParameters(true);

   //執行生成數字簽名
   SignedHashValue=rsaFormatter.CreateSignature(HashValue);


   //創建新的RSA對象
   RSACryptoServiceProvider RSA2 = new RSACryptoServiceProvider();
   //導入發佈的公鑰
   RSAParameters rasKeyInfo=new RSAParameters();
   rasKeyInfo.Modulus = myPublic.Modulus;
   rasKeyInfo.Exponent = myPublic.Exponent;
   RSA2.ImportParameters(rasKeyInfo);
   //使用公鑰進行解密
   RSAPKCS1SignatureFormatter RSAformatter = new RSAPKCS1SignatureFormatter(RSA2);
   //指定原加密算法
   RSAformatter.SetHashAlgorithm("SHA1");

   RSACryptoServiceProvider rsa3=new RSACryptoServiceProvider();
   RSAParameters rasKeyInfo2=new RSAParameters();
   rasKeyInfo2.Modulus = myPrivate.Modulus;
   rasKeyInfo2.Exponent = myPrivate.Exponent;
   rsa3.ImportParameters(rasKeyInfo2);
   RSAPKCS1SignatureDeformatter rsade=new RSAPKCS1SignatureDeformatter(rsa3);
   rsade.SetHashAlgorithm("SHA1");

   //進行比較 判斷簽名是否有效
   if(rsade.VerifySignature(HashValue, SignedHashValue))
   {
    Response.Write("經過驗證改簽名有效");
   }
   else
   {
    Response.Write("經過驗證改簽名無效");
   }

發佈了37 篇原創文章 · 獲贊 0 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章