Home
Browse all 647 examples
Download all 647 examples
Download sample chapters
Reviews
Errata
Acknowledgments
Links on .NET
Paradoxal Press

Buy directly from Paradoxal Press at $33.99 (Save 43%)



Category: Programming
Level: Beginner to seasoned
900 pages
ISBN-10 097661322-0
ISBN-13 978-097661322-0
$59.99 USA
$79.99 CANADA


Listing 6-22 extracted from chapter Security


Listing 6-21<     > Listing 6-23


This listing can be compiled with the command line:
csc.exe /target:exe Example_6_22.cs
Errors: 0 Warnings: 0


Example_6_22.cs
using System.Security.Cryptography;
class Program {
   static void Main() {
      string sMsg = "The message to encrypt!";
      string sEnc, sDec;
      System.Text.Encoding utf = new System.Text.UTF8Encoding();
      RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
      RSAParameters publicKey = rsa.ExportParameters( false );
      RSAParameters publicAndPrivateKey = rsa.ExportParameters( true );
      {
         RSACryptoServiceProvider rsaEncryptor = new 
                                    RSACryptoServiceProvider();
         rsaEncryptor.ImportParameters( publicKey );
         byte[] bMsg = utf.GetBytes(sMsg);
         byte[] bEnc = rsaEncryptor.Encrypt( bMsg, false );
         sEnc = System.Convert.ToBase64String( bEnc );
      }
      {
         RSACryptoServiceProvider rsaDecryptor = new 
                                    RSACryptoServiceProvider();
         rsaDecryptor.ImportParameters( publicAndPrivateKey );
         byte[] bEnc = System.Convert.FromBase64String(sEnc);
         byte[] bDec = rsaDecryptor.Decrypt( bEnc, false );
         sDec = utf.GetString( bDec );
      }
      System.Console.WriteLine("Message  : " + sMsg);
      System.Console.WriteLine("Encrypted: " + sEnc);
      System.Console.WriteLine("Decrypted: " + sDec);
   }
}	
Copyright Patrick Smacchia 2006 2007