Click here to Skip to main content
6,594,932 members and growing! (14,444 online)
Email Password   helpLost your password?
General Programming » Algorithms & Recipes » Algorithms     Intermediate

CSHA1 - A C++ Class Implementation of the SHA-1 Hash Algorithm

By Dominik Reichl

CSHA1 - A C++ class implementation of the SHA-1 hash algorithm
VC6, VC7Win2K, WinXPVS2008, Dev
Version:3 (See All)
Posted:19 Jun 2002
Updated:17 Mar 2009
Views:251,182
Bookmarked:96 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
49 votes for this article.
Popularity: 7.85 Rating: 4.65 out of 5
1 vote, 2.6%
1

2
1 vote, 2.6%
3
4 votes, 10.3%
4
33 votes, 84.6%
5

Contents

Description of the Secure Hash Algorithm SHA-1

The Secure Hash Algorithm SHA-1 is a cryptographically secure one-way hash algorithm. It was designed by the NIST (National Institute of Standards and Technology), along with the NSA (National Security Agency). SHA-1 is based on the Message Digest MD4 algorithm design principles by Ronald L. Rivest of MIT.

Well, I think I don't have to explain what you can do with cryptographic hash algorithms. For an example of what you can do with such algorithms, see this CodeProject article (CMD5 class).

For more information about SHA-1, see references [1] and [2].

CSHA1 Class Description

The CSHA1 class is an easy-to-use class for the SHA-1 hash algorithm.

If you want to test whether your implementation of the class is working, try the test vectors in the 'TestVectors' directory in the demo zip file. You can find the correct final hash values in the header file of the CSHA1 class.

Class members of the CSHA1 class:

  • void Reset(); 

    This member function resets the class. You have to call this method when using CSHA1 more than once. This method is called automatically in the constructor and the destructor of the class so if you only hash one single data stream you don't need to call Reset() manually.

  • void Update(const unsigned char* pbData, unsigned int uLen); 

    Use this method to hash in a data stream. Data in const unsigned char* pbData, length of stream has to be submitted in unsigned int uLen. Length in bytes.

  • bool HashFile(const TCHAR* tszFileName); 

    This method hashes file contents into the current state. If hashing was successful, the method returns true, otherwise false. If you use this member function, you don't need to make any call to the Update(...) method. After HashFile(...), you should call the Final() method immediately. You have to call Final() before getting the message digest of the file using the methods ReportHash(...) and GetHash(...).

  • void Final(); 

    When you have hashed in all data to hash, call this method. This will compute the final SHA-1 message digest and it is therefore needed to call this method before ReportHash(...) and GetHash(...).

  • void ReportHash(TCHAR* tszReport, REPORT_TYPE rtReportType); 

    After calling the Final method, you can get the message digest using this method. The result is stored as string in tszReport. Valid format types for uReportType are REPORT_HEX, REPORT_DIGIT and REPORT_HEX_SHORT. If you use REPORT_HEX the returned string looks like 5F A9 FB 34..., using REPORT_DIGIT this method returns the message digest in the form 129 67 5 98... . REPORT_HEX_SHORT is the same as REPORT_HEX, just without separating spaces.

  • void GetHash(unsigned char* pbDest); 

    If you don't want to get the hash in a pre-formatted string like ReportHash, you can use this method. This method copies the final message digest (call Final before!) to pbDest. pbDest must be able to hold at least 20 bytes (SHA-1 produces a 160-bit / 20-byte hash).

Hashing Binary Data and Strings

CSHA1 sha1;
sha1.Update(string0, strlen(string0));
sha1.Update(string1, strlen(string1));
sha1.Update(binary2, uSizeOfBufferBinary2);
sha1.Update(binary3, uSizeOfBufferBinary3);
sha1.Final();

sha1.ReportHash(szReport, CSHA1::REPORT_HEX_SHORT);
// or
sha1.GetHash(binaryArray);

I will comment each line of the example above now.

First declare an instance of the CSHA1 class:

CSHA1 sha1;

Now hash in the data like this:

sha1.Update((unsigned char *)szString, strlen(szString));

You can call this method as often as you wish.

When you hashed in all data, call the Final() member function:

sha1.Final();

If you want to get the final message digest as a pre-formatted string, use this:

sha1.ReportHash(szReport, CSHA1::REPORT_HEX_SHORT);

If you want to get the final message digest in "raw form":

sha1.GetHash(binaryArray); // Get the raw message digest bytes

Hashing Files

Hashing files is the same process as hashing strings and binary data but instead of using the Update method you use the HashFile member function of the class.

For more comments, see the string/binary data hashing example above.

CSHA1 sha1;
sha1.HashFile("TheFile.cpp"); // Hash in the contents of the file
                              // 'TheFile.cpp'
sha1.Final();

sha1.ReportHash(szReport, CSHA1::REPORT_HEX); // Get final hash as
                                              // pre-formatted string
// or
sha1.GetHash(binaryArray); // Get the raw message digest bytes to a
                           // temporary buffer

References

[1] RFC 3174: US Secure Hash Algorithm 1 (SHA1)
[2] Bruce Schneier, "Applied Cryptography", pages 442-445

Version History

  • 16 Mar 2009 - 1.8
    • Converted project files to Visual Studio 2008 format
    • Added Unicode support for HashFile utility method
    • Added support for hashing files using the HashFile method that are larger than 2 GB
    • HashFile now returns an error code instead of copying an error message into the output buffer
    • GetHash now returns an error code and validates the input parameter
    • Added ReportHashStl STL utility method
    • Added REPORT_HEX_SHORT reporting mode
    • Improved Linux compatibility of test program
  • 21 Dec 2006 - 1.7
    • Fixed buffer underrun warning that appeared when compiling with Borland C Builder (thanks to Rex Bloom and Tim Gallagher for the patch)
    • Breaking change: ReportHash writes the final hash to the start of the buffer, i.e. it's not appending it to the string anymore
    • Made some function parameters const
    • Added Visual Studio 2005 project files to demo project
  • 07 Feb 2005 - 1.6 Thanks to Howard Kapustein for the following patches:
    • You can set the endianness in your files, no need to modify the header file of the CSHA1 class anymore
    • Aligned data support
    • Made support/compilation of the utility functions (ReportHash and HashFile) optional (useful when bytes count, for example in embedded environments)
  • 1 Jan 2005 - 1.5
    • 64-bit compiler compatibility added
    • Made variable wiping optional (define SHA1_WIPE_VARIABLES)
    • Removed unnecessary variable initializations
    • ROL32 improvement for the Microsoft compiler (using _rotl)
  • 22 Jul 2004 - 1.4
    • CSHA1 now compiles fine with GCC 33 under MacOS X (thanks to Larry Hastings)
  • 17 Aug 2003 - 1.3
    • Fixed a small memory bug and made a buffer array a class member to ensure correct working when using multiple CSHA1 class instances at one time
  • 16 Nov 2002 - 1.2
    • Borlands C++ compiler seems to have problems with string addition using sprintf. Fixed the bug which caused the digest report function not to work properly. CSHA1 is now Borland compatible.
  • 11 Oct 2002 - 1.1
    • Removed two unnecessary header file includes and changed BOOL to bool. Fixed some minor bugs in the web page contents
  • 20 Jun 2002 - 1.0
    • First official release

That's it! Happy hashing!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Dominik Reichl


Member
Dominik started programming in Omikron Basic, a programming language for the good old Atari ST. After this, there was some short period of QBasic programming on the PC, but soon he began learning C++, which is his favorite language up to now.

Today, his programming experience includes C / C++ / [Visual] C++ [MFC], C#/.NET, Java, JavaScript, PHP and HTML and the basics of pure assembler.

He is interested in almost everything that has to do with computing, his special interests are security and data compression.

You can find his latest freeware, open-source projects and all articles on his homepage: http://www.dominik-reichl.de/
Occupation: Software Developer
Location: Germany Germany

Other popular Algorithms & Recipes articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 120 (Total in Forum: 120) (Refresh)FirstPrevNext
GeneralOutput bug Pinmembervcor12:26 5 Mar '09  
GeneralRe: Output bug PinmemberDominik Reichl23:55 17 Mar '09  
Generalsmall patch to use short hex output values Pinmemberthomasdev1:32 19 Feb '09  
GeneralRe: small patch to use short hex output values PinmemberDominik Reichl23:56 17 Mar '09  
GeneralRe: small patch to use short hex output values Pinmemberthomasdev0:51 18 Mar '09  
GeneralHMAC-SHA receiver processing? PinmemberAdam Harding13:52 3 Jun '08  
GeneralRe: HMAC-SHA receiver processing? PinmemberDominik Reichl6:11 4 Jun '08  
GeneralUseful! PinmemberDlt754:00 15 Nov '07  
GeneralUndefined reference to CSHA1::Update PinmemberRussellGilbert12:37 15 Jul '07  
AnswerRe: Undefined reference to CSHA1::Update Pinmemberbruno199910:37 5 Mar '08  
QuestionUTF16 encoding? PinmemberTuringMachine11:38 31 May '07  
AnswerRe: UTF16 encoding? PinmemberDominik Reichl23:10 31 May '07  
GeneralThere is a overrun bug Pinmembermissilry14:58 4 Dec '06  
GeneralRe: There is a overrun bug PinmemberDominik Reichl23:52 4 Dec '06  
QuestionSHA1 Hash does not give same hash as NET SHA1 PinmemberKilty2:34 19 Nov '06  
AnswerRe: SHA1 Hash does not give same hash as NET SHA1 PinmemberDominik Reichl8:53 30 Nov '06  
GeneralRe: SHA1 Hash does not give same hash as NET SHA1 PinmemberKilty9:13 30 Nov '06  
QuestionLimitation: Adding iostream Gives Compiler Errors Pinmemberalam009:53 20 May '06  
AnswerRe: Limitation: Adding iostream Gives Compiler Errors PinmemberKapali Viswanathan8:05 6 Jun '06  
Generalerreur LIBCD.lib Pinmemberramzi200623:54 18 Feb '06  
Generalconst char * Pinmemberbramp5:30 10 Jan '06  
GeneralThanks for contributing this PinmemberGadgetMan664:46 21 Dec '05  
Generalthanx a lot! Pinmemberzoz3:09 27 Nov '05  
Generaladding iostream and fstream Pinmembernmullane18:20 22 Oct '05  
GeneralRe: adding iostream and fstream PinmemberMiroslav Rajcic2:57 16 Oct '06  

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

PermaLink | Privacy | Terms of Use
Last Updated: 17 Mar 2009
Editor: Deeksha Shenoy
Copyright 2002 by Dominik Reichl
Everything else Copyright © CodeProject, 1999-2009
Web19 | Advertise on the Code Project