Archive for the ‘Encryption and DeCryption’ Category

Encryption and Decryption using Asymmetric Key

November 20, 2010 6 comments

Encryption and Decryption using Asymmetric Key
Asymmetric encryption has one public key and one private key.
The message is encrypted using the public key and can be only decrypted by the private key.
The recipient Asymmetrically encrypts the public key and transfers it to the message sender. The sender encrypts the message using this public key symmetrically and sends it back to the recipient, who decrypts the message using the private key.
Asymmetric algorithms are slow and are used only to encrypt small amount of data. They are generally used to encrypt and transfer symmetric Keys and IVs. The messages are encrypted symmetrically.
These techniques are used by HTTPS and SSL.
The key management is done by PKI- Private Key Infrastructure.

Asymmetric Algorithm Classes

  • KeyExchangeAlgorithm– Gets the name of the Key Exchange Algorithm.
  • KeySize – Gets and Sets the Key Size.
  • LegalKeySIze– Defines an array of Maximum and Minimum size of the key to be used.
  • SignatureAlgorithm – Gets the url of the xml file defining the signature algorithm.

Asymmetric Algorithm has 2 implementations

  • RSACryptoServiceProvider – It helps to Encrypt and Decrypt all messages with Asymmetrically. It is also uses as a wrapper for the unmanaged code.
  • DSACryptoServiceProvider – It helps to create Digital Signature messages. It is also uses as a wrapper for the unmanaged code.

RSACryptoServiceProvider provides the two following properties-

  • PersistKeyInCSP – Gets or Sets to indicate if the key should be in a persisted state in Crypto Service Provider. This will keep the key same every time  we want to reuse the key.
  • UseMachineKeyStore – Gets or Sets the value to indicate if you want to keep the key in machine key store of the user profile store.

Other properties are-

  • Encrypt – Encrypts with RSA Algorithm.
  • Decrypt– Decrypts with RSA Algorithm.
  • ImportParameters – Imports parameters for public keys or key pair.
  • ExportParameters – Exports RSA Parameter structure. False if passing only public key and True if passing both public and private key.
  • FromXMLString – Imports key pair  from XML string
  • SignData – Computes the hash value from the specified data and stores the signature to byte array.
  • HashData – Computes the signature from the hash value and stores the signature to byte array.
  • ValidData – Verifies if the specified data is similar to the computed specified data.
  • VerifyData – Verifies if the specified data is similar to the computed hash value.

Import, Export and Store Asymmetric Key

static void Main(string[] args)
CspParameters persistant = new CspParameters();
persistant.KeyContainerName = “persistantconatiner”;
RSACryptoServiceProvider getrsa = new RSACryptoServiceProvider(persistant);
getrsa.PersistKeyInCsp = true;
RSAParameters privatekey = getrsa.ExportParameters(true);

Encrypting and Decrypting Message in Asymmetric Encryption
static void Main(string[] args)
string msg = “The Hollywood Bowl. Good place to hang out.”;
RSACryptoServiceProvider getrsa = new RSACryptoServiceProvider();
byte[] msgbyte = Encoding.ASCII.GetBytes(msg);
byte[] encryptmsg = getrsa.Encrypt(msgbyte, false);
byte[] decryptmsg = getrsa.Decrypt(encryptmsg, false);



Encrypting and Decrypting With Symmetric Keys

November 18, 2010 Leave a comment

Symmetric Encryption
When the encoder and decoder both has the same key to Encrypt and Decrypt data, it is known as Symmetric Encryption.
In Symmetric Encryption The encoder uses a key to encode the data and transmits the data over a channel to the recipient. He then exchanges the key over another channel, specifically by voice, mail or in person, Anything but the channel over which the encrypted data is transmitted. The Key itself cannot be Encrypted.
The attacker can break the code if he has the key or by trying to know the key through hundreds of trial and error methods or brute force. Its a lengthy process but the data can still be deciphered. One must change the key at regular interval.
The Symmetric Encryption method cannot be used over the web applications or web services because it is not possible to deliver the key at the same instance to the client at the same time of data access.

There are 5 ways to implement Symmetric Encryption –

  • RijndaelManaged – 128 Bit to 256 Bit Encryption. Can be used in partially managed environment.
  • AESManaged – 128 Bit. Advances Encryption Standard. Implements RijndaelManaged Encryption. Used with fixed Size Block and Iteration Count.
  • DES – 56Bit. Data Encryption Standard. Short Length Key
  • TripleDES – 156 Bit. Only 112 Bit are utilized. Implements DES Three Times.
  • RC2 – Variable Bit.

Properties of Symmetric Encryption
The Symmetric Encryption is derived from System.Security.Cryptography.SymmetricAlgorithm Class and has the following properties –

  • BlockSize – The size data that is being encrypted at one time.
  • FeedBackSize – The Size of data that is fed back to the successive encryption or decryption
  • Initiation Vector(IV) – Helps in securing the first block of data further.
  • Key – Used to Encrypt and Decrypt the data.
  • KeySize – Sets the size of the key.
  • LegalBlockSize – Gets the block size in an Array and stores the range from minimum to maximum size.
  • LegalKeySize – Gets the Key size in an Array and stores the range from minimum to maximum size.
  • Mode – Set to CipherMode Enumeration, usually in Cipher Block Chaining.
  • Padding –  Helps to determine the difference between the encrypted block and the size of the data to be Ciphered or Deciphered.

And the following Methods

  • CreateEncryptor – Helps to Encrypt Data
  • CreateDecryptor –  Helps to Decrypt Data
  • GenerateKey – Generates the Random Key
  • GenerateIV – Generated the Random Initiation Vector
  • ValidKeySize – Check to See if the generated key is valid for the Symmetric Algorithm.

Generating Symmetric Key and Initiation Vector(IV)
Generating Key and IV from password and SALT-

static void Main(string[] args)
string pass= “t4P@55w0R9”;
RijndaelManaged alg = new RijndaelManaged();
byte[] salt = Encoding.ASCII.GetBytes(“Using this salt;”);
Rfc2898DeriveBytes mykey = new Rfc2898DeriveBytes(pass, salt);
alg.Key = mykey.GetBytes(alg.KeySize / 8);
alg.IV = mykey.GetBytes(alg.BlockSize / 8);

Encryption and DeCryption using Symmetric Keys

static void Main(string[] args)
string infile = @”c:\in.txt”;
string outfile = @”C:\out.enc”;
FileStream inf = new FileStream(infile, FileMode.Open, FileAccess.Read);
FileStream outf = new FileStream(outfile, FileMode.OpenOrCreate, FileAccess.Write);
SymmetricAlgorithm Symmetricalg = new RijndaelManaged();
byte[] filedata = new byte[inf.Length];
inf.Read(filedata, 0, (int)inf.Length);
ICryptoTransform encryptor = Symmetricalg.CreateEncryptor();
CryptoStream stream = new CryptoStream(outf, encryptor, CryptoStreamMode.Write);
stream.Write(filedata, 0, filedata.Length);

string infile2 = @”C:\out.enc”;
string outfile2 = @”C:\final.txt”;
FileStream inf2 = new FileStream(infile2, FileMode.Open, FileAccess.Read);
FileStream outf2 = new FileStream(outfile2, FileMode.OpenOrCreate, FileAccess.Write);
byte[] filedata2 = new byte[inf2.Length];
inf2.Read(filedata2, 0, (int)inf2.Length);
ICryptoTransform decryptor = Symmetricalg.CreateDecryptor();
CryptoStream stream2 = new CryptoStream(outf2, decryptor, CryptoStreamMode.Write);
stream2.Write(filedata2, 0, filedata2.Length);

//in.txt contains the data that you want to encrypt.

Categories: C#, Encryption and DeCryption Tags: ,
%d bloggers like this: