PublicKey Cryptography : Encryption « Security « C# / CSharp Tutorial






using System;
using System.Security.Cryptography;

  class Class1
  {
    static void Main(string[] args)
    {
      string dataToSign = "this is a test.";
      byte[] data_Bytes = System.Text.Encoding.ASCII.GetBytes( dataToSign );
      
      SHA1Managed sha1 = new SHA1Managed();
      byte[] hash_Bytes = sha1.ComputeHash( data_Bytes );
    
      DSACryptoServiceProvider dsa = new DSACryptoServiceProvider(); 
      DSASignatureFormatter sigFormatter = new DSASignatureFormatter(dsa);
      sigFormatter.SetHashAlgorithm("SHA1");
      byte[] signedHash = sigFormatter.CreateSignature( hash_Bytes );

      byte[] remote_SignedHash = signedHash;
      byte[] remote_HashedValue = hash_Bytes;

      DSASignatureDeformatter sigDeformatter = new DSASignatureDeformatter( dsa );
      sigDeformatter.SetHashAlgorithm( "SHA1" );

      Console.WriteLine(sigDeformatter.VerifySignature( remote_HashedValue, remote_SignedHash ));

      RSACryptoServiceProvider rsa=  new RSACryptoServiceProvider();
      byte[] dataToEncrypt = System.Text.Encoding.Unicode.GetBytes( "Encrypt THIS!" );
      byte[] encrypted_Bytes;
      byte[] decrypted_Bytes;

      encrypted_Bytes = rsa.Encrypt( dataToEncrypt, false );
      Console.WriteLine("RSA-encrypted data is {0} bytes long.", encrypted_Bytes.Length);
      decrypted_Bytes = rsa.Decrypt( encrypted_Bytes, false );
      Console.WriteLine("RSA-decrypted string is {0}.", System.Text.Encoding.Unicode.GetString( decrypted_Bytes ));
    }
  }








35.14.Encryption
35.14.1.Symmetric Encryption
35.14.2.PublicKey Cryptography
35.14.3.Secret Key Cryptography: RijndaelManaged
35.14.4.Create a new instance of the CipherData class using CipherReference information.
35.14.5.Use DataReference to encrypt and decrypt multiple XML elements using different session keys.