Click here to Skip to main content
15,881,898 members
Articles / Programming Languages / C++
Article

A C++ Implementation of the Blowfish Encryption/Decryption method

Rate me:
Please Sign up or sign in to vote.
4.89/5 (56 votes)
26 Sep 2001Ms-PL3 min read 958K   12.8K   145   122
An article presenting a C++ implementation of the Blowfish encryption/decryption method

Introduction

Blowfish is an encryption algorithm that can be used as a replacement for the DES or IDEA algorithms. It is a symmetric (i.e. uses the same secret key for both encryption and decryption) block cipher (encrypts data in 8-byte blocks) that uses a variable-length key, from 32 (4 bytes) bits to 448 bits (56 bytes). Blowfish was designed in 1993 by Bruce Schneier as an alternative to existing encryption algorithms. Designed with 32-bit instruction processors in mind, it is significantly faster than DES. Since its origin, it has been analyzed considerably. Blowfish is unpatented, license-free, and available free for all uses. The algorithm consists of two parts: a key-expansion part and a data-encryption part. Key expansion converts a variable key of at least 4 and at most 56 bytes into several subkey arrays totalling 4168 bytes. Blowfish has 16 rounds. Each round consists of a key-dependent permutation, and a key and data-dependent substitution. All operations are XORs and additions on 32-bit words. The only additional operations are four indexed array data lookups per round. Blowfish uses a large number of subkeys. These keys must be precomputed before any data encryption or decryption.

A more detailed article describing the Blowfish algorithm can be found at http://www.schneier.com/blowfish.html

The C++ implementation presented in this article was tested against the test vectors provided by Eric Young at http://www.counterpane.com/vectors.txt. The results were identical with one exception which in my opinion could be a typing error in the referenced Internet file.

Implementation

The public user interface of the CBlowfish class is given bellow:

class CBlowFish
{
public:
  //Constructor - Initialize the P and S boxes for a given Key
  CBlowFish(unsigned char* ucKey, size_t n, <BR>            const SBlock& roChain = SBlock(0UL,0UL));
  //Resetting the chaining block
  void ResetChain();
  // Encrypt/Decrypt Buffer in Place
  void Encrypt(unsigned char* buf, size_t n, int iMode=ECB);
  void Decrypt(unsigned char* buf, size_t n, int iMode=ECB);
  // Encrypt/Decrypt from Input Buffer to Output Buffer
  void Encrypt(const unsigned char* in, unsigned char* out, 
               size_t n, int iMode=ECB);
  void Decrypt(const unsigned char* in, unsigned char* out, 
               size_t n, int iMode=ECB);
};

In the constructor, a user-supplied key material of specified size is used to generate the subkey arrays. Also the chain block is initialized with the specified value.

The function ResetChain() is used to reset the chaining block before starting a new encryption or decryption operation.

The first variant of the Encrypt() function is used for in place encryption of a block of data of the specified size applying the specified operation mode. The block size should be a multiple of 8. This function can operate in the following modes: ECB, CBC or CFB. In ECB mode, chaining is not used. If the same block is encrypted twice with the same key, the resulting ciphertext blocks are the same. In CBC mode a ciphertext block is obtained by first XOR-ing the plaintext block with the previous ciphertext block, and encrypting the resulting value. In CFB mode a ciphertext block is obtained by encrypting the previous ciphertext block and XOR-ing the resulting value with the plaintext. The operation mode is specified in the iMode parameter with ECB being the default value. For the second variant of the Encrypt() function the encryption result is delivered in an output buffer.

The Decrypt() functions are the reverse of the Encrypt() functions presented above.

Usage Examples

The use of CBlowfish class is very easy. In the first code snippet example a key of 8 bytes in size is applied to an 8 byte block. The initial chain block is a null block. The block "aaaabbbb" is encrypted and then decrypted back.

try
{
  char szHex[17];
  //Initialization
  CBlowFish oBlowFish((unsigned char*)"abcdefgh", 8);
  char szDataIn[] = "aaaabbbb";
  char szDataOut[17] = "\0\0\0\0\0\0\0\0";
  //Encryption
  oBlowFish.Encrypt((unsigned char*)szDataIn, (unsigned char*)szDataOut, 8);
  CharStr2HexStr((unsigned char*)szDataIn, szHex, 8);
  cout << szHex << endl;
  CharStr2HexStr((unsigned char*)szDataOut, szHex, 8);
  cout << szHex << endl;
  memset(szDataIn, 0, 8);
  //Decryption
  oBlowFish.Decrypt((unsigned char*)szDataOut, (unsigned char*)szDataIn, 8);
  CharStr2HexStr((unsigned char*)szDataIn, szHex, 8);
  cout << szHex << endl;
}
catch(exception& roException)
{
  cout << roException.what() << endl;
}

In the next code snippet example a key of 16 bytes in size is applied to a larger block of data of 48 bytes size (the block of data size should be a multiple of the block size which is always 8 bytes). The initial chain block is a null block. The block "ababababccccccccababababccccccccababababcccccccc" is encrypted and then decrypted back in all the operation modes (ECB, CBC and CFB). Notice that for the chaining operating modes the chain block has to be reset before decrypting back.

try
{
  CBlowFish oBlowFish((unsigned char*)"1234567890123456", 16);
  char szDataIn1[49] = "ababababccccccccababababccccccccababababcccccccc";
  char szDataIn[49];
  char szDataOut[49];
  memset(szDataIn, 0, 49);
  memset(szDataOut, 0, 49);

  //Test ECB
  strcpy(szDataIn, szDataIn1);
  memset(szDataOut, 0, 49);
  oBlowFish.Encrypt((unsigned char*)szDataIn, 
                    (unsigned char*)szDataOut, 48, CBlowFish::ECB);
  memset(szDataIn, 0, 49);
  oBlowFish.Decrypt((unsigned char*)szDataOut, 
                    (unsigned char*)szDataIn, 48, CBlowFish::ECB);

  //Test CBC
  oBlowFish.ResetChain();
  strcpy(szDataIn, szDataIn1);
  memset(szDataOut, 0, 49);
  oBlowFish.Encrypt((unsigned char*)szDataIn, 
                    (unsigned char*)szDataOut, 48, CBlowFish::CBC);
  memset(szDataIn, 0, 49);
  oBlowFish.ResetChain();
  oBlowFish.Decrypt((unsigned char*)szDataOut, 
                    (unsigned char*)szDataIn, 48, CBlowFish::CBC);

  //Test CFB
  oBlowFish.ResetChain();
  strcpy(szDataIn, szDataIn1);
  memset(szDataOut, 0, 49);
  oBlowFish.Encrypt((unsigned char*)szDataIn, 
                    (unsigned char*)szDataOut, 48, CBlowFish::CFB);
  memset(szDataIn, 0, 49);
  oBlowFish.ResetChain();
  oBlowFish.Decrypt((unsigned char*)szDataOut, 
                    (unsigned char*)szDataIn, 48, CBlowFish::CFB);
  cout << endl;
}
catch(exception& roException)
{
  cout << "Exception: " 
       << roException.what() << endl;
}

I am interested in any opinions and new ideas about this implementation. The project Blowfish.zip attached to this article includes the source code of the presented CBlowfish class and some test code.

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)


Written By
Web Developer
Romania Romania
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralI can't decrypt using this algo Pin
Nirav Thakkar31-Jan-04 9:51
Nirav Thakkar31-Jan-04 9:51 
Question8-byte padding? Pin
Jacques Cooper24-Dec-03 10:55
Jacques Cooper24-Dec-03 10:55 
GeneralMultiple of 8 Problem Pin
Hermaphrodyte14-Dec-03 11:26
Hermaphrodyte14-Dec-03 11:26 
GeneralConstructor question Pin
alex.barylski3-Dec-03 0:22
alex.barylski3-Dec-03 0:22 
GeneralRe: Constructor question Pin
George Anescu3-Dec-03 5:42
George Anescu3-Dec-03 5:42 
QuestionHelp me please?? Pin
xxhimanshu4-Nov-03 23:09
xxhimanshu4-Nov-03 23:09 
QuestionHow to use the encryption/decryption with string with lengths not a multiple of 8 bytes? Pin
breakpoint7-Oct-03 1:30
breakpoint7-Oct-03 1:30 
AnswerRe: How to use the encryption/decryption with string with lengths not a multiple of 8 bytes? Pin
Chris Losinger5-Nov-03 1:18
professionalChris Losinger5-Nov-03 1:18 
Questionhow to add padding support? Pin
vcken15-Sep-03 0:39
vcken15-Sep-03 0:39 
Generaldiffcult to write code Pin
firesw29-May-03 20:05
firesw29-May-03 20:05 
QuestionSuggestion for a utility that generates keys? Pin
Anonymous31-Oct-02 4:23
Anonymous31-Oct-02 4:23 
AnswerRe: Suggestion for a utility that generates keys? Pin
Anonymous30-Mar-04 23:58
Anonymous30-Mar-04 23:58 
GeneralMinor suggestion Pin
nde_plume29-Oct-02 9:34
nde_plume29-Oct-02 9:34 
GeneralRe: Minor suggestion Pin
George Anescu4-Nov-02 7:40
George Anescu4-Nov-02 7:40 
GeneralExcellent work Pin
Anonymous23-Sep-02 15:09
Anonymous23-Sep-02 15:09 
QuestionMalicious bug or??? Pin
snakeeye8-Sep-02 7:48
snakeeye8-Sep-02 7:48 
AnswerRe: Malicious bug or??? Pin
Chris Losinger8-Sep-02 7:57
professionalChris Losinger8-Sep-02 7:57 
Generalhelp me please?? Pin
xxhimanshu4-Nov-03 23:13
xxhimanshu4-Nov-03 23:13 
AnswerRe: Malicious bug or??? Pin
jskrewson13-Oct-02 19:54
jskrewson13-Oct-02 19:54 
GeneralCode Pin
14-Aug-02 1:03
suss14-Aug-02 1:03 
GeneralRe: Code Pin
George Anescu4-Nov-02 9:09
George Anescu4-Nov-02 9:09 
Generalgcc problems Pin
Kjetil Haga9-May-02 16:47
Kjetil Haga9-May-02 16:47 
GeneralRe: gcc problems Pin
Kjetil Haga9-May-02 17:11
Kjetil Haga9-May-02 17:11 
GeneralFinally Pin
alex.barylski15-Mar-02 17:20
alex.barylski15-Mar-02 17:20 
QuestionAny suggestions of sites for encyption ? Pin
24-Feb-02 7:49
suss24-Feb-02 7:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.