This article is a mirror article of machine translation, please click here to jump to the original article.

View: 30040|Reply: 7

[Source] RSA generates public and private keys, as well as encryption and decryption

[Copy link]
Posted on 12/11/2015 10:12:29 AM | | | |
  1. public static class RSACryptoProvider
  2.     {
  3.         /// <summary>
  4.         /// RSA解密
  5.         /// </summary>
  6.         /// <param name="base64code">需要进行解密的密文字符串</param>
  7.         /// <param name="privateKey">私钥</param>
  8.         /// <returns>解密后的明文</returns>
  9.         public static string Decrypt(string base64code, string privateKey)
  10.         {
  11.             UnicodeEncoding ByteConverter = new UnicodeEncoding();

  12.             RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
  13.             RSA.FromXmlString(privateKey);

  14.             byte[] encryptedData;
  15.             byte[] decryptedData;

  16.             encryptedData = Convert.FromBase64String(base64code);

  17.             decryptedData = RSADecrypt(encryptedData, RSA.ExportParameters(true), false);

  18.             return ByteConverter.GetString(decryptedData);
  19.         }

  20.         /// <summary>
  21.         /// RSA分段解密;用于对超长字符串解密
  22.         /// </summary>
  23.         /// <param name="toEncryptString">需要进行解密的字符串</param>
  24.         /// <param name="publickKey">私钥</param>
  25.         /// <returns>解密后的明文</returns>
  26.         public static string SectionDecrypt(string base64code, string privateKey)
  27.         {
  28.             UnicodeEncoding ByteConverter = new UnicodeEncoding();
  29.             RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
  30.             RSA.FromXmlString(privateKey);

  31.             Byte[] CiphertextData = Convert.FromBase64String(base64code);

  32.             int MaxBlockSize = RSA.KeySize / 8;

  33.             if (CiphertextData.Length <= MaxBlockSize)
  34.             {
  35.                 byte[] decryptedData;

  36.                 decryptedData = RSADecrypt(CiphertextData, RSA.ExportParameters(true), false);

  37.                 return ByteConverter.GetString(decryptedData);
  38.             }

  39.             MemoryStream CrypStream = new MemoryStream(CiphertextData);

  40.             MemoryStream PlaiStream = new MemoryStream();

  41.             Byte[] Buffer = new Byte[MaxBlockSize];

  42.             int BlockSize = CrypStream.Read(Buffer, 0, MaxBlockSize);

  43.             while (BlockSize > 0)
  44.             {
  45.                 Byte[] ToDecrypt = new Byte[BlockSize];
  46.                 Array.Copy(Buffer, 0, ToDecrypt, 0, BlockSize);

  47.                 Byte[] Plaintext = RSADecrypt(ToDecrypt, RSA.ExportParameters(true), false);
  48.                 PlaiStream.Write(Plaintext, 0, Plaintext.Length);

  49.                 BlockSize = CrypStream.Read(Buffer, 0, MaxBlockSize);
  50.             }

  51.             return ByteConverter.GetString(PlaiStream.ToArray());
  52.         }

  53.         /// <summary>
  54.         /// RSA加密
  55.         /// </summary>
  56.         /// <param name="toEncryptString">需要进行加密的字符串</param>
  57.         /// <param name="publicKey">公钥</param>
  58.         /// <returns>加密后的密文</returns>
  59.         public static string Encrypt(string toEncryptString, string publicKey)
  60.         {
  61.             UnicodeEncoding ByteConverter = new UnicodeEncoding();

  62.             byte[] dataToEncrypt = ByteConverter.GetBytes(toEncryptString);

  63.             byte[] encrytedData;

  64.             RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

  65.             RSA.FromXmlString(publicKey);

  66.             encrytedData = RSAEncrypt(dataToEncrypt, RSA.ExportParameters(false), false);

  67.             string base64code = Convert.ToBase64String(encrytedData);

  68.             return base64code;
  69.         }

  70.         /// <summary>
  71.         /// RSA分段加密;用于对超长字符串加密
  72.         /// </summary>
  73.         /// <param name="toEncryptString">需要进行加密的字符串</param>
  74.         /// <param name="publickKey">公钥</param>
  75.         /// <returns>加密后的密文</returns>
  76.         public static string SectionEncrypt(string toEncryptString, string publickKey)
  77.         {
  78.             string base64code = string.Empty;

  79.             UnicodeEncoding ByteConverter = new UnicodeEncoding();

  80.             byte[] dataToEncrypt = ByteConverter.GetBytes(toEncryptString);

  81.             RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

  82.             RSA.FromXmlString(publickKey);

  83.             int MaxBlockSize = RSA.KeySize / 8 - 11;

  84.             if (dataToEncrypt.Length <= MaxBlockSize)
  85.             {
  86.                 byte[] encrytedData;

  87.                 encrytedData = RSAEncrypt(dataToEncrypt, RSA.ExportParameters(false), false);

  88.                 base64code = Convert.ToBase64String(encrytedData);

  89.                 return base64code;
  90.             }

  91.             MemoryStream plaiStream = new MemoryStream(dataToEncrypt);

  92.             MemoryStream CrypStream = new MemoryStream();

  93.             Byte[] Buffer = new Byte[MaxBlockSize];

  94.             int BlockSize = plaiStream.Read(Buffer, 0, MaxBlockSize);

  95.             while (BlockSize > 0)
  96.             {
  97.                 Byte[] ToEncrypt = new Byte[BlockSize];
  98.                 Array.Copy(Buffer, 0, ToEncrypt, 0, BlockSize);

  99.                 Byte[] Cryptograph = RSAEncrypt(ToEncrypt, RSA.ExportParameters(false), false);
  100.                 CrypStream.Write(Cryptograph, 0, Cryptograph.Length);

  101.                 BlockSize = plaiStream.Read(Buffer, 0, MaxBlockSize);
  102.             }

  103.             base64code = Convert.ToBase64String(CrypStream.ToArray(), Base64FormattingOptions.None);

  104.             return base64code;
  105.         }
  106.         /// <summary>
  107.         /// RSA生成公钥和私钥
  108.         /// </summary>
  109.         /// <returns></returns>
  110.         public static string[] GenerateKeys()
  111.         {
  112.             try
  113.             {
  114.                 string[] sKeys = new String[2];
  115.                 RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
  116.                 sKeys[0] = rsa.ToXmlString(true);
  117.                 sKeys[1] = rsa.ToXmlString(false);
  118.                 return sKeys;
  119.             }
  120.             catch (Exception)
  121.             {
  122.                 return null;
  123.             }
  124.         } 

  125.         private static byte[] RSAEncrypt(byte[] DataToEncrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
  126.         {
  127.             RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

  128.             RSA.ImportParameters(RSAKeyInfo);

  129.             return RSA.Encrypt(DataToEncrypt, DoOAEPPadding);
  130.         }

  131.         private static byte[] RSADecrypt(byte[] DataToDecrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
  132.         {
  133.             RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

  134.             RSA.ImportParameters(RSAKeyInfo);

  135.             return RSA.Decrypt(DataToDecrypt, DoOAEPPadding);
  136.         }

  137.     }
Copy code






Previous:Use the array name as the argument of the function The reverse order of the array
Next:Store the array in reverse order, and the parameter in the function inv is a pointer variable
Posted on 12/11/2015 10:51:32 AM |
Posted on 12/11/2015 11:22:50 AM |
Are you also engaged in this encryption and decryption algorithm now? After learning C, I will start working on that algorithm. Can you give me some guidance?
 Landlord| Posted on 12/11/2015 11:40:32 AM |
xiaoweier posted on 2015-12-11 11:22
Are you also engaged in this encryption and decryption algorithm now? After learning C, I will start working on that algorithm. Can you give me some guidance?

Let's look at the example first:



On the code:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;

  5. namespace WebSite1.Security
  6. {
  7.     public struct RSA_Keys
  8.     {
  9.         public const string Public = "<RSAKeyValue><Modulus>mcqqC6vyZSach3/PpaG+HlgI05Pu3OXX37DiLDi2wWltpcCwF3Z52dZmcrKKIwwTD0q58i46u9hiBr6VdsOU2UQEozvX5cM9gJ4EUUxq0K5PhLoRWfrCUQ1/i8d5cJ1D6a7jSJhXar4U8mM2ERiYymBfUn8zERE9qebxqwPCr0E=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
  10.         public const string Private = "<RSAKeyValue><Modulus>mcqqC6vyZSach3/PpaG+HlgI05Pu3OXX37DiLDi2wWltpcCwF3Z52dZmcrKKIwwTD0q58i46u9hiBr6VdsOU2UQEozvX5cM9gJ4EUUxq0K5PhLoRWfrCUQ1/i8d5cJ1D6a7jSJhXar4U8mM2ERiYymBfUn8zERE9qebxqwPCr0E=</Modulus><Exponent>AQAB</Exponent><P>08NgiedL36cKVuTfNdNbtbe8OjUElcPfSQ/PZaTHkum8+aeu44Pb3XIFF4YEetRdJpbwvopb7J0sS8elR28EXQ==</P><Q>uesZTcA7e8PrPzHsROWZOnFwu+vw41yqZenUAo5R0mvCzAe23QjTM+AXSuNihEtfA0KoIuneucWY/xXLj/VoNQ==</Q><DP>vk+uKQFXbO5gGmuiNmt21j8DyIPxVO8tcinlSAHo4h1yGiQaxpmwNLnN3bAxwnmsJYwtW/BYYLN4JbqMzT/2eQ==</DP><DQ>VGYkk4Y7uqCjD4ojPteX6s8KpVSjgyNS+3bd1tcyz7o5sROjcM4LytXk3QtCctogZMOCvm66vEy2er4zLcPzLQ==</DQ><InverseQ>o5MLJDmubOgGWBDpPY0r80cGDFJ0r8hLLZ8vFlVkkhNkSMuoszM0RgoIPAn/R3YsD8rIxH3CldhfPuMuXljaLg==</InverseQ><D>foCqJzelB3cfQoXrs/67eBJKEF+bF7EoRSQmpuFv0uB6BOHe9y3JRVqKosYhwnpoIygAlClavrFa0Nlr8GkowdeGQD3dW4pjMWGwC2dVub9Lot3Vm5bWEDy8QUw9e/jR7+SXfXyrknylN4sozrJtVTeb//a1x4HV1D5elQtx7cE=</D></RSAKeyValue>";
  11.     }
  12. }
Copy code

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;

  5. namespace WebSite1.Security
  6. {
  7.     /// <summary>
  8.     /// MD5加密
  9.     /// </summary>
  10.     public class MD5CryptoProvider
  11.     {
  12.         public static string Encrypt(string text)
  13.         {
  14.             return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(text, "MD5");
  15.         }
  16.     }
  17. }
Copy code
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.UI;
  6. using System.Web.UI.WebControls;
  7. using WebSite1.Security;

  8. namespace WebSite1
  9. {
  10.     public partial class _Default : Page
  11.     {
  12.         protected void Page_Load(object sender, EventArgs e)
  13.         {

  14.         }

  15.         protected void btntiao_Click(object sender, EventArgs e)
  16.         {
  17.             string tid = "test";
  18.             string rsa = RSACryptoProvider.SectionEncrypt(MD5CryptoProvider.Encrypt(tid.ToUpper()), RSA_Keys.Public);
  19.             Response.Redirect("About.aspx?tid=" + tid + "&sign=" + Uri.EscapeDataString(rsa));
  20.         }
  21.     }
  22. }
Copy code
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.UI;
  6. using System.Web.UI.WebControls;
  7. using WebSite1.Security;

  8. namespace WebSite1
  9. {
  10.     public partial class About : Page
  11.     {
  12.         protected void Page_Load(object sender, EventArgs e)
  13.         {
  14.             if (!IsPostBack)
  15.             {
  16.                 string tid=Request.QueryString["tid"];
  17.                 string rsa = Request.QueryString["sign"];
  18.                 if (MD5CryptoProvider.Encrypt(tid.ToUpper()) == RSACryptoProvider.SectionDecrypt(rsa, RSA_Keys.Private))
  19.                 {
  20.                     Response.Write("成功!中途没有被修改!");
  21.                 }
  22.                 else {
  23.                     Response.Write("失败!中途被修改过了!");
  24.                 }
  25.             }
  26.         }
  27.     }
  28. }
Copy code
This one is not given a full score?????
 Landlord| Posted on 12/11/2015 11:42:55 AM |

Top wool thread look at the 4th floor
Posted on 12/11/2015 11:44:33 AM |
Xiao Zhazha Posted on 2015-12-11 11:40
Let's look at the example first:

I don't understand what you're doing above.
Posted on 12/11/2015 2:07:00 PM |
Xiao Zhazha Posted on 2015-12-11 11:42
Top wool thread look at the 4th floor

 Landlord| Posted on 6/1/2023 8:51:19 PM |
c# RSA encryption decryption Segmented encryption and segmented decryption
https://www.itsvse.com/thread-2779-1-1.html
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com