#include "StdAfx.h"
#include "Interno.h"
#include "osrng.h"
using namespace std;
using namespace CryptoPP;
void CInterno::InternalEncrypt(RSAES_PKCS1v15_Encryptor* pEncryptor, const unsigned char * pbIn, int nLengthInBytes, unsigned char ** ppbOut)
{
// Calculate the chunk sizes
int nMaxMsgLen = pEncryptor->FixedMaxPlaintextLength();
int nChunks = (nLengthInBytes%nMaxMsgLen) ? nLengthInBytes/nMaxMsgLen+1 : nLengthInBytes/nMaxMsgLen;
int nCipherLen = pEncryptor->CiphertextLength(nMaxMsgLen);
int nChunkLen;
// Allocate more than will be needed
int nBufferSize = nCipherLen * (nChunks+1);
byte * pbBuffer = new byte[nBufferSize];
byte * pbOut = pbBuffer;
memset(pbOut, 0, nBufferSize);
int nTotalEncryptedBytes = 0;
// Encrypt in chunks
AutoSeededRandomPool rng;
nLengthOutBytes = 0;
for(int n=1; n <= nChunks; n++)
{
// Find the chunk length
nChunkLen = (n == nChunks) ? (nLengthInBytes - (n-1)*nMaxMsgLen) : nMaxMsgLen;
pEncryptor->Encrypt(rng, ((byte*)pbIn) + (n-1)*nMaxMsgLen, nChunkLen, pbOut);
// Keep the last length
pbOut += pEncryptor->CiphertextLength(nChunkLen);
nLengthOutBytes += pEncryptor->CiphertextLength(nChunkLen);
//DebugPrint("Chunk %d: (%d bytes)\r\n%s", n, nChunkLen, ToBinaryString(pbBuffer, nLengthOutBytes).c_str());
}
//
// Copy bytes out (caller must deallocate memory, no garbage collection on new!)
//
*ppbOut = new unsigned char[nLengthOutBytes];
memcpy(*ppbOut, pbBuffer, nLengthOutBytes);
// free buffer
delete pbBuffer;
}
void CInterno::InternalDecrypt(RSAES_PKCS1v15_Decryptor* pDecryptor, const unsigned char * pbIn, int nLengthInBytes, unsigned char ** ppbOut)
{
// Find the maximum message length
int nMaxMsgLen = pDecryptor->FixedCiphertextLength();
int nChunks = (nLengthInBytes%nMaxMsgLen) ? nLengthInBytes/nMaxMsgLen+1 : nLengthInBytes/nMaxMsgLen;
int nChunkLen;
int nBufferSize = pDecryptor->MaxPlaintextLength(nMaxMsgLen) * (nChunks+1);
byte * pbBuffer = new byte[nBufferSize];
byte * pbOut = pbBuffer;
memset(pbOut, 0, nBufferSize);
int nTotalDecryptedBytes = 0;
// Decrypt chunks
AutoSeededRandomPool rng;
nLengthOutBytes = 0;
for(int n=1; n <= nChunks; n++)
{
nChunkLen = (n == nChunks) ? (nLengthInBytes - (n-1)*nMaxMsgLen) : nMaxMsgLen;
unsigned int unLen = pDecryptor->MaxPlaintextLength(nChunkLen);
size_t nOutputLength = 0;
nOutputLength = pDecryptor->Decrypt(rng, ((byte*)pbIn) + (n-1)*nMaxMsgLen, nChunkLen, pbOut).messageLength;
pbOut += nOutputLength;
nLengthOutBytes += nOutputLength;
}
//
// Copy bytes out (caller must deallocate memory, no garbage collection on new!)
//
*ppbOut = new unsigned char[nLengthOutBytes];
memcpy(*ppbOut, pbBuffer, nLengthOutBytes);
// free memory
delete pbBuffer;
}