5,427,303 members and growing! (15,695 online)
Email Password   helpLost your password?
General Programming » Cryptography & Security » Cryptography     Intermediate License: The Microsoft Public License (Ms-PL)

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

By George Anescu

An article presenting a C++ implementation of the Blowfish encryption/decryption method
VC6, C++Windows, NT4, Win2KVS6, Visual Studio, Dev

Posted: 26 Sep 2001
Updated: 26 Sep 2001
Views: 227,026
Bookmarked: 74 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
59 votes for this Article.
Popularity: 7.88 Rating: 4.45 out of 5
2 votes, 4.9%
1
0 votes, 0.0%
2
1 vote, 2.4%
3
6 votes, 14.6%
4
32 votes, 78.0%
5

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, 
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)

About the Author

George Anescu



Occupation: Web Developer
Location: Romania Romania

Other popular Cryptography & Security articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 108 (Total in Forum: 108) (Refresh)FirstPrevNext
Subject  Author Date 
Generalhow to change the algorithm from "unsigned char" to "unsigned long"memberpinzoka4:41 17 Aug '08  
QuestionCannot compile thismemberSaib0t6:09 22 Jun '08  
Generaluse "1" as password to encrypt a file and then use "11" as password to decrypt file. why this can success?membershocker.cn1:08 27 May '08  
GeneralRe: use "1" as password to encrypt a file and then use "11" as password to decrypt file. why this can success?membershocker.cn20:35 27 May '08  
GeneralTrouble decrypting using javamemberrameshk013:14 11 Sep '07  
GeneralRe: Trouble decrypting using javamemberdubbele onzin4:44 27 Nov '07  
GeneralRe: Trouble decrypting using javamemberpku200920:49 5 Aug '08  
Generalnot able to encrypt and decrypt a big message with spacesmemberartiguptahere3:01 18 May '07  
Generalhow to test ?memberSoftware_Specialist9:42 22 Apr '07  
GeneralC# code for Blowfishmembermu3hm20:38 10 Apr '07  
GeneralProblems with the implementation of the codemember__TSX__12:41 22 Nov '06  
AnswerRe: Problems with the implementation of the codememberGSc_Dev9:08 6 Mar '07  
GeneralDecrypting possible with different passwordmemberM Zah2:09 26 Jul '06  
GeneralRe: Decrypting possible with different passwordmemberxcompscix8:04 31 Jul '06  
AnswerRe: Decrypting possible with different passwordmemberJMB198411:34 6 Nov '06  
QuestionLittle EndianmemberMr. S11:36 13 Apr '06  
Generalproblemmemberquistiun14:59 22 Mar '06  
GeneralRe: problemmemberbreakpoint22:17 23 Mar '06  
GeneralRe: problemmemberquistiun15:41 24 Mar '06  
GeneralVery nicememberJim Xochellis21:52 13 Mar '06  
GeneralCommercial using of sourcesmemberAndreyLG22:38 18 Jan '06  
GeneralKnown length of decrypted Stringmembercwanner10:25 19 Oct '05  
GeneralRe: Known length of decrypted StringmemberNxTitle13:01 23 May '07  
Generalneed a help on implement the codememberTorune17:06 2 Sep '05  
GeneralRe: need a help on implement the codememberbreakpoint2:45 9 Apr '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 26 Sep 2001
Editor: Chris Maunder
Copyright 2001 by George Anescu
Everything else Copyright © CodeProject, 1999-2008
Web12 | Advertise on the Code Project