Tuesday, 20 June 2017

Hash Functions and Encoding and Decoding of Integer in Crypto++

/*
	This program shows encoding of an integer into a byte array
	and again decoding the byte array into integer.

	This encoding and decoding is basically used when we need to give a byte array to SHA256 or SHA512
*/

#include <iostream>
using std::cout;
using std::endl;
using std::cin;

#include <cryptopp/integer.h>
using CryptoPP::Integer;

#include <cryptopp/sha.h>
using CryptoPP::SHA512;


Integer hashOfInteger(const Integer &a) // {0,1}* -> Zp*
{
	cout<<"Finding hash of "<<a<<endl;
	// using SHA512 here
	int byteCount=a.BitCount()/8;
	if(a.BitCount()%8!=0)
		byteCount++;
	byte byteArray[byteCount];	
	byte digest[SHA512::DIGESTSIZE];
	a.Encode(byteArray,byteCount);
	
	// now byte array contains bytes corresponding to the Integer a

	SHA512().CalculateDigest(digest,byteArray,byteCount);

	Integer result;
	result.Decode(digest,SHA512::DIGESTSIZE);
	return result;
}

int main()
{

	int n;
	cin>>n;
	cout<<"result  = "<<hashOfInteger(Integer::Power2(n))<<endl;
	return 0;
}

No comments:

Post a Comment