thieumao

RSA Demo - toi uu code de nhin hon

Aug 29th, 2013
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.10 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Security.Cryptography;
  6. using System.IO;
  7.  
  8. namespace RSA_Demo
  9. {
  10.     class RSA_Test1
  11.     {
  12.         public void GenRSA()
  13.         {
  14.             try
  15.             {
  16.                 #region Sinh khoa
  17.                 RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider();
  18.                 // Export public key
  19.                 string publicKey = rsaProvider.ToXmlString(false);
  20.                 // Export private/public key pair
  21.                 string privateKey = rsaProvider.ToXmlString(true);
  22.                 // in ra man hinh
  23.                 Console.WriteLine("private key----------------");
  24.                 Console.WriteLine(privateKey);
  25.                 Console.WriteLine("public key-----------------");
  26.                 Console.WriteLine(publicKey);
  27.                 // Ban ro
  28.                 string _message = "Noi dung ban ro";
  29.                 Console.WriteLine("Message: ");
  30.                 Console.WriteLine(_message);
  31.                 #endregion
  32.  
  33.                 #region ma hoa
  34.                 byte[]  plainBytes = Encoding.Unicode.GetBytes(_message);
  35.                 byte[]  encryptedBytes = rsaProvider.Encrypt(plainBytes, false);
  36.                 string encrypt_message = Encoding.UTF8.GetString(encryptedBytes);
  37.                 Console.WriteLine("encrypted...");
  38.                 Console.WriteLine(encrypt_message);
  39.                 #endregion
  40.  
  41.                 #region giai ma
  42.                 byte[] decryptedBytes = rsaProvider.Decrypt(encryptedBytes, false);
  43.                 string decrypted_string = Encoding.Unicode.GetString(decryptedBytes);
  44.                 Console.WriteLine("decrypted...");
  45.                 Console.WriteLine(decrypted_string);
  46.                 #endregion
  47.  
  48.             }
  49.             catch (Exception ex)
  50.             {
  51.                 // Any errors? Show them
  52.                 Console.WriteLine("Exception generating a new key pair! More info:");
  53.                 Console.WriteLine(ex.Message);    
  54.             }
  55.             Console.ReadKey();
  56.         }
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment