Cet article est un article miroir de traduction automatique, veuillez cliquer ici pour accéder à l’article original.

Vue: 30040|Répondre: 7

[Source] RSA génère des clés publiques et privées, ainsi que du chiffrement et du déchiffrement

[Copié le lien]
Publié sur 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.     }
Code de copie






Précédent:Utilisez le nom du tableau comme argument de la fonction L’ordre inverse du tableau
Prochain:Stockez le tableau dans l’ordre inverse, et le paramètre de la fonction inv est une variable pointeur
Publié sur 11/12/2015 10:51:32 |
Publié sur 11/12/2015 11:22:50 |
Êtes-vous aussi engagé dans cet algorithme de chiffrement et de déchiffrement aujourd’hui ? Après avoir appris C, je commencerai à travailler sur cet algorithme. Pouvez-vous me donner quelques conseils ?
 Propriétaire| Publié sur 11/12/2015 11:40:32 |
Xiaoweier a posté le 11-12-2015 à 11:22
Êtes-vous aussi engagé dans cet algorithme de chiffrement et de déchiffrement aujourd’hui ? Après avoir appris C, je commencerai à travailler sur cet algorithme. Pouvez-vous me donner quelques conseils ?

Regardons d’abord l’exemple :



Sur le 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. }
Code de copie

  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. }
Code de copie
  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. }
Code de copie
  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. }
Code de copie
Celui-ci ne reçoit pas de note complète ?????
 Propriétaire| Publié sur 11/12/2015 11:42:55 |

Regarde le fil de laine du haut au 4e étage
Publié sur 11/12/2015 11:44:33 |
Xiao Zhazha Publié le 11-12-2015 à 11:40
Regardons d’abord l’exemple :

Je ne comprends pas ce que tu fais plus haut.
Publié sur 11/12/2015 14:07:00 |
Xiao Zhazha Publié le 11-12-2015 à 11:42
Regarde le fil de laine du haut au 4e étage

 Propriétaire| Publié sur 01/06/2023 20:51:19 |
Chiffrement c# RSA Chiffrement segmenté et déchiffrement segmenté
https://www.itsvse.com/thread-2779-1-1.html
Démenti:
Tous les logiciels, supports de programmation ou articles publiés par Code Farmer Network sont uniquement destinés à l’apprentissage et à la recherche ; Le contenu ci-dessus ne doit pas être utilisé à des fins commerciales ou illégales, sinon les utilisateurs assumeront toutes les conséquences. Les informations sur ce site proviennent d’Internet, et les litiges de droits d’auteur n’ont rien à voir avec ce site. Vous devez supprimer complètement le contenu ci-dessus de votre ordinateur dans les 24 heures suivant le téléchargement. Si vous aimez le programme, merci de soutenir un logiciel authentique, d’acheter l’immatriculation et d’obtenir de meilleurs services authentiques. En cas d’infraction, veuillez nous contacter par e-mail.

Mail To:help@itsvse.com