Bouncy Castle - .Net Implementation  Triple DES Algorithm

In this article, we will go through a simple example to demonstrate Encryption and Decryption techniques using Triple DES algorithms. We will use Bouncy Castle APIs for performing below steps.

Encryption steps -

Select an input message - Input message can be in the form of a string which the user enters, or a stream e.g. File stream, memory stream or Network stream. There can be two cases depending upon the input length 

a. The length is modulo 8 bytes i.e. it is possible to divide the input message into blocks of 8 bytes. In this case, there would be no padding needed.

b. If the length is not in multiples of 8, we would need padding to compete the last block. In this scenario, we should consider the PaddedBufferedBlockCipher class, which pads according to the selected industry standards.

Generate a Triple DES key. (secret key) - We will use the CipherKeyGenerator class from the Bouncy Castle apis. CipherKeyGenerator is the base class for symmetric key generation The Cipher Key Generator needs to know the strength of the key as well as the Cipher for which to generate the key. In the following examples, the ciphers are DESEDE with ECB mode and Triple DES with CBC Cipher as cipher mode.

Create a Triple DES algorithm object and select the ECB mode - Triple DES cipher can be created either directly instantiating the DESESE engine or using the CipherUtilities class which has a collection of various ciphers along with the mode and the Padding information.

Initialize the Cipher - We have to initialize the cipher with the symmetric key. Additionally, we need to specify if we are going to use the cipher for encryption or for decryption mechanism.

Input message has a block of bytes that is occurring twice. Since we have selected ECB mode (default mode), each block is encrypted separately with the cipher key. Therefore, the output message also, has repetition of encrypted block corresponding to the repeated input block

An attacker can probably recognize the pattern of repetition and thus have clue about the input message.

On analyzing the output generated by DES 3 CBC mode, we find that the first block is same as the first block of output by DES3 ECB mode, but the remaining blocks are never repeated. This is because the CBC mode uses the feedback mechanism and encryption each block depends upon the previous encrypted block.

Bouncy Castle - .Net Implementation  AES Algorithm

As mentioned previously, AES algorithms are stronger than DES and Triple DES algorithms. The below example implements an AES encryption logic using the CFB mode. Also, we pass an Initialization vector to the cipher, which is used for process the first cipher block.