Main Page | Namespace List | Class Hierarchy | Alphabetical List | Class List | Directories | File List | Namespace Members | Class Members | File Members | Related Pages

SHA1HashFunction.cc

00001 /*
00002  * Copyright 2003 Michael A. Marsh, Cornell University. All rights reserved.
00003  * This software is released under the modified BSD license.
00004  * See the file LICENSE in the top-level directory for details.
00005  */
00006 //
00007 // $Id: SHA1HashFunction.cc,v 1.4 2004/05/19 15:56:47 mmarsh Exp $
00008 //
00009 // $Log: SHA1HashFunction.cc,v $
00010 // Revision 1.4  2004/05/19 15:56:47  mmarsh
00011 // *** empty log message ***
00012 //
00013 // Revision 1.3  2003/11/04 22:31:48  mmarsh
00014 // *** empty log message ***
00015 //
00016 //
00017 
00018 #include <openssl/sha.h>
00019 #include <openssl/evp.h>
00020 
00021 #include "SHA1HashFunction.h"
00022 
00023 using namespace CODEX_Ciphers;
00024 
00025 HashFunction::ustring*
00026 SHA1HashFunction::operator()( const ustring& buff ) const
00027 {
00028    EVP_MD_CTX ctx;
00029    EVP_DigestInit( &ctx, EVP_sha1() );
00030    EVP_DigestUpdate( &ctx, buff.data(), buff.length() );
00031    unsigned char output[ SHA_DIGEST_LENGTH ]; // 20 bytes = 160 bits
00032    unsigned int s;
00033    EVP_DigestFinal( &ctx, output, &s );
00034    return new ustring( output, SHA_DIGEST_LENGTH );
00035 }
00036 
00037 HashFunction::ustring*
00038 SHA1HashFunction::operator()( const ustring& buff, unsigned int len ) const
00039 {
00040    unsigned int bytesNeeded = (len+7)/8;
00041    EVP_MD_CTX ctx;
00042    EVP_MD_CTX_init( &ctx );
00043    ustring* retVal = new ustring;
00044    ustring junkBuff;
00045 
00046    // now loop
00047    unsigned char i = 0;
00048    while ( bytesNeeded > 0 )
00049    {
00050       junkBuff.push_back(i);
00051       i = ( i < 255 ) ? i+1 : 0;
00052       EVP_DigestInit_ex( &ctx, EVP_sha1(), 0 ); // uses default implementation
00053       EVP_DigestUpdate( &ctx, buff.data(), buff.length() );
00054       EVP_DigestUpdate( &ctx, junkBuff.data(), junkBuff.length() );
00055       unsigned char output[ SHA_DIGEST_LENGTH ]; // 20 bytes = 160 bits
00056       unsigned int s;
00057       EVP_DigestFinal_ex( &ctx, output, &s );
00058       unsigned int write_length = ( s < bytesNeeded ) ? s : bytesNeeded;
00059       retVal->reserve( retVal->capacity() + write_length );
00060       for ( unsigned int j = 0 ; j < write_length ; ++j )
00061       {
00062          retVal->push_back(output[j]);
00063       }
00064       bytesNeeded -= write_length;
00065    }
00066 
00067    EVP_MD_CTX_cleanup( &ctx );
00068    return retVal;
00069 }

Generated on Fri May 6 17:41:15 2005 for COrnell Data EXchange (CODEX) by  doxygen 1.4.1