Skip to main content

Encrypting and Decrypting Data in .Net



Namespace: System.Security.Cryptography

Encrypt your important information specially when transmitting across network.

Encryption Algorithms (Symmetric Algorithms):

These are the algorithm with single key, which produce data in the same length as the original.

RijndaclManaged Algorithm: Key Length 128 through 256 with 32 bit increments. Its only managed encryption algorithm implemented in .NET Framework.

RC2: Algorithm to replace DES. Key Length is Variable.

DES: Key Length is 56 bits.

TripleDES: Key length is 156 bits. It encrypts data three times with DES.

All these algorithm classes derive from SymmetricAlgorithm class.

Major properties of SymmetricAlgorithm:

1.       BlockSize: Who much data will be encrypted at a given time in bits.
2.       FeedbackSize: It can’t be greater than BlockSize. It is the no. of bits returned after encryption/decryption.
3.       IV: A random no. generated when an instance of the SymmetricAlgorithm is created of GenratedIV method is called. It should be of the same size as BlockSize. One may define a specific IV for his application.
4.       Keys: Get or sets the Key. It will be generated automatically if you don’t define.
5.       KeySize: It is automatically chosen of the biggest size supported by the platform. But it must choose manually to ensure that the sender and recipient have the same KeySize.
6.       LegalBlockSizes: Gets the block sizes that are supported by the symmetric algorithm.
7.       LegalKeySizes: Gets the key sizes that are supported by the symmetric algorithm.
8.       Mode: Define the mode for encryption/decryption. Here are the operational modes:
a.       CBC: Before encrypting i+1 block, take its XOR with its Block and then encrypt
b.      CFB: Before encrypting, it divides Block into bytes then places bytes in shift registers, cipher a byte then gives shift to the whole block.
c.       CTS: Cipher the whole text in one cycle, and produces the same length text.
d.      ECB: Ciphers plain-text block by block, hence produces same cipher text for same blocks with same keys.
e.      OFB: Similar to CBC, difference is in the filling of the Shift registers.
9.       Padding: Specify the mode of padding that is about who the last block will be filled, if it does not fill the entire block.

SymmetricAlgorithm also provides few methods those are shared among child classes.
CreateDecryptor
Overloaded. Creates a symmetric decryptor object.
CreateEncryptor
Overloaded. Creates a symmetric encryptor object.
GenerateIV
When overridden in a derived class, generates a random initialization vector (IV) to use for the algorithm.
GenerateKey
When overridden in a derived class, generates a random key (Key) to use for the algorithm.
ValidKeySize
Determines whether the specified key size is valid for the current algorithm.

Establishing Symmetric Key:
Use a specialized key, or use GenrateKey method to generate a random key, save this key to decrypt data in future.

One can also use System.Security.Cryptography.Rfc2898DeriveBytes to convert use password into a Key, along with password also provide the IV, SecretSalt and number of iterations. These three values should also be known at the time of decryption.

Remember while generating Key by calling the GetBytes method of Rfc2898DerivesBytes you have to provide the number of Bytes of which key should be, while KeySize is in Bits. So, Convert Bits to Bytes before passing in value.

CreateEncryptor/CreateDecryptor both returns ICryptoTransfrom which have the following properties:

Name
Description
TransformBlock
Transforms the specified region of the input byte array and copies the resulting transform to the specified region of the output byte array.
TransformFinalBlock
Transforms the specified region of the specified byte array.

You can also create CryptoStream Object to directly read/write to file. CryptoStream constructor requires the following parameters:
stream [FileStream]              The stream on which to perform the cryptographic transformation.
transform [ICryptoStream] The cryptographic transformation that is to be performed on the stream.
mode                                           One of the CryptoStreamMode values. [Read | Write]


Asymmetric Encryption Algorithm

This encryption algorithm relies on key pairs that are Public key and private. Public is open to everyone and he can encrypt data with that key and send to servers. Server must have the private key in order to decrypt the cipher text.

It is slow as compared to Symmetric algorithms and it is not recommended to encrypt large files with it.

One can use Asymmetric encryption to share symmetric keys, and then for further data communication they can use symmetric algorithm. Just like HTTPS and SSL do.

Asymmetric algorithm classes inherit from System,Security.Cryptography.AsemmetricAlgorithm. It has the following properties.

KeyExchangeAlgorithm: Gets the key exchange algorithm, being a developer you need not to worry about it.

KeySize: Typical size is 182 bits. .Net Supports for RSA is 384 through 16384 bits with 8 bits increment. Microsoft Base/Enhanced Cryptographic Provider should be installed.

LegelKeySize: Array of available sizes for the Key.
SignatureAlgorithm: Gets URL of an XML describing signature algorithm.

There are two implementations of the AsymmetricAlgorithm.

DSACryptoServiceProvider:
It’s also a wrapper around unmanaged implementation of the DSA. It’s used for digitally signing messages.

RSACryptoServiceProvider:
It’s a wrapper around the unmanaged implementation of the RSA provided by Cryptography API. Default constructor provides you with strongest defaults, that you can save for further use. It defines the following properties also:

PersistKeyInCsp: set it to true, if you want to reuse the key without exporting it.
UseMachineKeyStore: Indicates that whether to store the key in computer’s key store or user profile store.

Public Methods

Name
Description
Clear 
Releases all resources used by the AsymmetricAlgorithm class. (Inherited from AsymmetricAlgorithm.)
Create 
Overloaded. Allows specific implementations of RSA to be instantiated. (Inherited from RSA.)
Decrypt
Decrypts data with the RSA algorithm.
Encrypt
Encrypts data with the RSA algorithm.
ExportCspBlob
Exports a blob containing the key information associated with an RSACryptoServiceProvider object.
ExportParameters
Overridden. Exports the RSAParameters.
FromXmlString 
Initializes an RSA object from the key information from an XML string. (Inherited from RSA.)
ImportCspBlob
Imports a blob that represents RSA key information.
ImportParameters
Overridden. Imports the specified RSAParameters.
ToXmlString 
Creates and returns an XML string containing the key of the current RSA object. (Inherited from RSA.)

[Export/Import]Parameter uses RSAParameters structure. This structure has the following properties:

Name
Description
D
Represents the D parameter for the RSA algorithm. Private Key.
DP
Represents the DP parameter for the RSA algorithm.
DQ
Represents the DQ parameter for the RSA algorithm.
Exponent
Represents the Exponent parameter for the RSA algorithm. Also known as e, short part of the public key.
InverseQ
Represents the InverseQ parameter for the RSA algorithm.
Modulus
Represents the Modulus parameter for the RSA algorithm. Also known as n, the long part of the public key.
P
Represents the P parameter for the RSA algorithm.
Q
Represents the Q parameter for the RSA algorithm.

Storing Key Pairs for later use:
Use the Overloaded constructer and pass it CspParameters structure. Set CspParameter.KeyContainerName property and set property RSACryptoServiceProvider,PersistKeyInCsp. The .Net framework will automatically store key and will retrieve the key next time your application runs by using the KeyConainerName.


Encrypt/Decrypting Data:
Encrypt/Decrypt method requires two parameters,

1. byte[] rgb. Containing data to encrypt/decrypt
2. bool fOAEP. True means use OAEP(on windows xp and > only) otherwise PKCS#1 v1.5 Padding.

Example of using:

//Create a UnicodeEncoder to convert between byte array and string.
ASCIIEncoding ByteConverter = new ASCIIEncoding();
string dataString = "Data to Encrypt";

byte[] dataToEncrypt = ByteConverter.GetBytes(dataString);
byte[] encryptedData;
byte[] decryptedData;

RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider();

Console.WriteLine("Original Data: {0}", dataString);

encryptedData = RSAalg.Encrypt(dataToEncrypt, false);

Console.WriteLine("Encrypted Data: {0}", ByteConverter.GetString(encryptedData));

decryptedData = RSAalg.Decrypt(encryptedData, false);

Console.WriteLine("Decrypted plaintext: {0}",
                                                         ByteConverter.GetString(decryptedData));














Comments

Popular posts from this blog

Culture Information and Localization in .NET

Namespace: System.Globalization CultureInfo Class:                 It provides information like the Format of numbers and dates, Culture’s Calendar, Culture’s language and sublanguage (if applicable), Country and region of the culture. The Basic use of CultureInfo class is shown here: • How string Comparisons are performed • How Number Comparison & Formats are performed • Date Comparison and Formats. • How resources are retrieved and used. Cultures are grouped into three categories: Invariant Culture : It’s Culture Insensitive. It can be used to build some trial application. It can be also used to build an application with hard-coded expiry date that ignores cultures. But using it for every comparison will be incorrect and inappropriate. Neutral Culture : English(en), Frensh(fr), and Spanish(sp). A neutral culture is related to language but it’s not related to specific regi...

Concept of App Domain in .Net

Creating Application Domains: Application domain is just like process, provides separate memory space, and isolates from other code. But it’s quite light weight. It also provides the following advantages: 1-       Reliability : If a domain crashes, it can be unloaded. Hence doesn’t affect the other assemblies. 2-       Efficiency : Loading all assemblies in one domain can be cumbersome and can make the process heavy but Appdomains are efficient in this manner. Important properties of AppDomain: ApplicationIdentity , ApplicationTrust , BaseDirectory , CurrentDomain , DomainManager , DomainDirectory , Evidence , FriendlyName , ID , RelativeSearchPath , SetupInformation , ShadowCopyFiles . Important methods of AppDomain: ApplyPolicy , CreateCOMInstanceFrom , CreateDomain , CreateInstance (Assembly). To create an AppDomain: AppDomain adomain = AppDomain.CreateDomain(“D”); To execute an assembly:...

ASP.NET Working With Data-Bound Web Server Controls

Suppose we have: List<Car> vCars = new List<Car>(); There are three types of databound controls: Simple databound controls(List, AdRotater), Composite data bound controls(GridView, DetailsView, FormView that inherit from CompositeDataBoundControl), and Hierarchal data bound controls (TreeView, Menu).   DataBoundControl has a DataBind method that can be used when data is ready. It calls DataBind for child controls as well. Page.DataBind() will call DataBind for all child controls. Using DataSource Objects:                                       BaseDataBound control exposes DataSource property that accepts objects that implement IEnumerable , IListSource , IDataSource , or IHierarchalDataSource . DataSourceID accepts ID of SqlDataSource . If both specified Data...