Este artículo es un artículo espejo de traducción automática, por favor haga clic aquí para saltar al artículo original.

Vista: 30040|Respuesta: 7

[Fuente] RSA genera claves públicas y privadas, así como cifrado y descifrado

[Copiar enlace]
Publicado en 11/12/2015 10:12:29 | | | |
  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.     }
Copiar código






Anterior:Utiliza el nombre del array como argumento de la función El orden inverso del array
Próximo:Almacena el array en orden inverso, y el parámetro en la función inv es una variable puntero
Publicado en 11/12/2015 10:51:32 |
Publicado en 11/12/2015 11:22:50 |
¿También estás involucrado ahora en este algoritmo de cifrado y descifrado? Después de aprender C, empezaré a trabajar en ese algoritmo. ¿Puedes darme algún consejo?
 Propietario| Publicado en 11/12/2015 11:40:32 |
Xiaoweier publicó el 11-12-2015 a las 11:22
¿También estás involucrado ahora en este algoritmo de cifrado y descifrado? Después de aprender C, empezaré a trabajar en ese algoritmo. ¿Puedes darme algún consejo?

Veamos primero el ejemplo:



Sobre el código:

  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. }
Copiar código

  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. }
Copiar código
  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. }
Copiar código
  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. }
Copiar código
A este no se le otorga la puntuación completa?????
 Propietario| Publicado en 11/12/2015 11:42:55 |

Mira el hilo superior de lana en la cuarta planta
Publicado en 11/12/2015 11:44:33 |

No entiendo qué haces arriba.
Publicado en 11/12/2015 14:07:00 |
Xiao Zhazha Publicado el 11-12-2015 11:42
Mira el hilo superior de lana en la cuarta planta

 Propietario| Publicado en 1/6/2023 20:51:19 |
Descifrado de cifrado RSA en c# Cifrado segmentado y descifrado segmentado
https://www.itsvse.com/thread-2779-1-1.html
Renuncia:
Todo el software, materiales de programación o artículos publicados por Code Farmer Network son únicamente para fines de aprendizaje e investigación; El contenido anterior no se utilizará con fines comerciales o ilegales; de lo contrario, los usuarios asumirán todas las consecuencias. La información de este sitio proviene de Internet, y las disputas de derechos de autor no tienen nada que ver con este sitio. Debes eliminar completamente el contenido anterior de tu ordenador en un plazo de 24 horas desde la descarga. Si te gusta el programa, por favor apoya el software genuino, compra el registro y obtén mejores servicios genuinos. Si hay alguna infracción, por favor contáctanos por correo electrónico.

Mail To:help@itsvse.com