Skip to Main Content

Java Security

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Getting different MD5 hashes in cryptoAPI and java messageDigest

843811Nov 30 2005 — edited Dec 6 2005
Hi,

I am writing a java application to produce a hash value for a string
which should give me the same hash value as a c++ code which uses CryptoAPI.
I am including code snippets of the c++ and the java codes...Plese tell me
if the reason i am getting different hash values is because the java code is
using a different provider. If so where do i get the provider and how do i use it
in this code.

try
	{
		if (0==::CryptAcquireContext(&hProv,NULL,MS_DEF_PROV, PROV_RSA_FULL,CRYPT_MACHINE_KEYSET))
		{
			//throwing exception
		}
		// Create the hash object...
		if (0==::CryptCreateHash(hProv,CALG_MD5,0,0,&hHash))
		{
			//throwing exception
		}

		// Actually hash the data
		if (0==::CryptHashData(hHash,reinterpret_cast<CONST BYTE *>(bsData),::SysStringByteLen(bsData),0))
		{
			//throwing exception
		}

		// Extract the actual hash value from the hash object
		// But first get the buffer size required to store the same...
		if (0==::CryptGetHashParam(hHash,HP_HASHVAL,NULL,&dwLen,0))
		{
			//throwing exception
		}

		// Try allocating memory for the buffer...
		pBuffer=static_cast<BYTE *>(::malloc(dwLen));
		if (NULL==pBuffer)
		{
			//throwing exception
		}
		memset(pBuffer,'\0',sizeof(pBuffer));

		// Now extract the hash value into this buffer
		if (0==::CryptGetHashParam(hHash,HP_HASHVAL,pBuffer,&dwLen,0))
		{
			//throwing exception
		}

		// Capture the hash value into a BSTR

		::SysFreeString(*pbsHashValue);
		*pbsHashValue=NULL;

		// Allocate the new string
		*pbsHashValue=::SysAllocStringLen((unsigned short *)pBuffer,dwLen/2);
		if (NULL==*pbsHashValue)
		{
			//throwing exception		
		}
	}catch(char *e){
		//cleanup and show error if any.
	}
The hash i get for "srikanth" is "b*.DB����.�o��.." or
" 98 42 46 68 66 229 180 166 206 46 223 111 211 203 46 46 0"

The java Code:
{
	MessageDigest messageDigest;
	byte []		l_bytes		= null;
	String p_password = "srikanth";
	try{
		messageDigest = MessageDigest.getInstance("MD5");
		messageDigest.update(p_password.getBytes (),	0,	p_password.length ());
		l_bytes	= messageDigest.digest();
		BigInteger hash = new BigInteger( 1, l_bytes );
		System.out.println("hash :"+hash);
		String hpassword = hash.toString( 16 );
		System.out.println(hpassword);
	
	}catch(NoSuchAlgorithmException e){
		System.out.println("No Such Algorithm Exception");
		return;
	}
	
}
and output here is :
hash :98295845500620623440969102971712815427
49f3175a93cd22f5e345bca772f7c143

Please let me know where am i going wrong.
Thanks,
Srik.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 3 2006
Added on Nov 30 2005
6 comments
446 views