Guest User

Untitled

a guest
Mar 10th, 2021
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Security.Cryptography;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using System.Xml.Serialization;
  9.  
  10. namespace test4000
  11. {
  12. public class RsaEnc
  13. {
  14. private static RSACryptoServiceProvider csp = new RSACryptoServiceProvider(2048);
  15. private RSAParameters _privateKey;
  16. private RSAParameters _publicKey;
  17.  
  18.  
  19. public RsaEnc()
  20. {
  21. _privateKey = csp.ExportParameters(true);
  22. _publicKey = csp.ExportParameters(false);
  23. }
  24.  
  25. public string PublicKeyString()
  26. {
  27. var sw = new StringWriter();
  28. var xs = new XmlSerializer(typeof(RSAParameters));
  29. xs.Serialize(sw, _publicKey);
  30. return sw.ToString();
  31. }
  32.  
  33. public string Encrypt(string plainText)
  34. {
  35. csp = new RSACryptoServiceProvider();
  36. csp.ImportParameters(_publicKey);
  37.  
  38. var data = Encoding.Unicode.GetBytes(plainText);
  39. var cypher = csp.Encrypt(data, false);
  40. return Convert.ToBase64String(cypher);
  41. }
  42. public string Decrypte(string cypherText)
  43. {
  44. var dataBytes = Convert.FromBase64String(cypherText);
  45. csp.ImportParameters(_publicKey);
  46. var plainext = csp.Decrypt(dataBytes, false);
  47. return Encoding.Unicode.GetString(plainext);
  48. }
  49. }
  50. class Program
  51. {
  52. static void Main(string[] args)
  53. {
  54. RsaEnc rs = new RsaEnc();
  55. string cypher = String.Empty;
  56. Console.WriteLine($"PublicKey: \n {rs.PublicKeyString()}\n");
  57.  
  58. Console.WriteLine("entrez votre texte à crypter");
  59. var text = Console.ReadLine();
  60. if (text != String.Empty)
  61. {
  62. cypher = rs.Encrypt(text);
  63. Console.WriteLine($"Texte codé:\n {cypher} \n");
  64. }
  65.  
  66. Console.WriteLine("Appuyez sur la touche entre pour décrypter");
  67. Console.ReadLine();
  68. var plainText = rs.Decrypte(cypher);
  69. Console.WriteLine("Texte décrypté \n");
  70. Console.WriteLine(plainText);
  71. Console.ReadLine();
  72. }
  73. }
  74. }
  75.  
Add Comment
Please, Sign In to add comment