From a5ef8c01b351bbdb7d4d57625bdb09cd20b871f2 Mon Sep 17 00:00:00 2001 From: ElenaSubbotina Date: Fri, 18 May 2018 15:28:31 +0300 Subject: [PATCH] PdfWriter - encrypt in AES256 --- DesktopEditor/graphics/pro/graphics.pro | 1 - PdfReader/Src/SecurityHandler.cpp | 1 - PdfWriter/PdfWriter.pro | 3 + PdfWriter/PdfWriterTest/PdfWriterTest.cpp | 492 ++++------------ PdfWriter/Src/Document.cpp | 88 ++- PdfWriter/Src/Document.h | 3 +- PdfWriter/Src/Encrypt.cpp | 662 ++++++++-------------- PdfWriter/Src/Encrypt.h | 80 +-- PdfWriter/Src/EncryptDictionary.cpp | 121 ++-- PdfWriter/Src/EncryptDictionary.h | 3 +- PdfWriter/Src/FontCidTT.cpp | 31 +- PdfWriter/Src/Info.cpp | 4 +- PdfWriter/Src/Objects.cpp | 46 +- PdfWriter/Src/Pages.cpp | 112 ++-- PdfWriter/Src/Streams.cpp | 56 +- PdfWriter/Src/Types.h | 5 - UnicodeConverter/UnicodeConverter.cpp | 20 +- 17 files changed, 613 insertions(+), 1115 deletions(-) diff --git a/DesktopEditor/graphics/pro/graphics.pro b/DesktopEditor/graphics/pro/graphics.pro index 55ff6c7c03..28b8b9ef2a 100644 --- a/DesktopEditor/graphics/pro/graphics.pro +++ b/DesktopEditor/graphics/pro/graphics.pro @@ -139,7 +139,6 @@ SOURCES += $$LIB_GRAPHICS_PRI_PATH/freetype-2.5.2/src/base/ftbbox.c \ $$LIB_GRAPHICS_PRI_PATH/freetype-2.5.2/src/base/ftlcdfil.c \ $$LIB_GRAPHICS_PRI_PATH/freetype-2.5.2/src/base/ftmm.c \ $$LIB_GRAPHICS_PRI_PATH/freetype-2.5.2/src/base/ftotval.c \ - $$LIB_GRAPHICS_PRI_PATH/freetype-2.5.2/src/base/ftobjs.c \ $$LIB_GRAPHICS_PRI_PATH/freetype-2.5.2/src/base/ftpatent.c \ $$LIB_GRAPHICS_PRI_PATH/freetype-2.5.2/src/base/ftpfr.c \ $$LIB_GRAPHICS_PRI_PATH/freetype-2.5.2/src/base/ftsynth.c \ diff --git a/PdfReader/Src/SecurityHandler.cpp b/PdfReader/Src/SecurityHandler.cpp index 1cbc1d3665..32ed08d2ab 100644 --- a/PdfReader/Src/SecurityHandler.cpp +++ b/PdfReader/Src/SecurityHandler.cpp @@ -205,7 +205,6 @@ namespace PdfReader } else { - // TO DO: Error "Weird encryption info" } oFileID.Free(); diff --git a/PdfWriter/PdfWriter.pro b/PdfWriter/PdfWriter.pro index 3150063fb2..90c9ebc5cf 100644 --- a/PdfWriter/PdfWriter.pro +++ b/PdfWriter/PdfWriter.pro @@ -17,6 +17,9 @@ DEFINES += PDFWRITER_USE_DYNAMIC_LIBRARY LIBS += -L$$CORE_BUILDS_LIBRARIES_PATH -lUnicodeConverter -lkernel -lgraphics +DEFINES += CRYPTOPP_DISABLE_ASM +LIBS += -lCryptoPPLib + DEFINES += NOMINMAX core_windows { diff --git a/PdfWriter/PdfWriterTest/PdfWriterTest.cpp b/PdfWriter/PdfWriterTest/PdfWriterTest.cpp index 22f35e7005..1a90236ca6 100644 --- a/PdfWriter/PdfWriterTest/PdfWriterTest.cpp +++ b/PdfWriter/PdfWriterTest/PdfWriterTest.cpp @@ -29,12 +29,22 @@ * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode * */ -// PdfWriterTest.cpp : Defines the entry point for the console application. +// PdfReaderTest.cpp : Defines the entry point for the console application. // -#include "stdafx.h" +#include +#include +#include +#include +#include "../OnlineOfficeBinToPdf.h" #include "../PdfRenderer.h" +#include "../../DesktopEditor/fontengine/ApplicationFonts.h" + +#include "../../DesktopEditor/raster/Metafile/MetaFile.h" +#include "../../DesktopEditor/raster/BgraFrame.h" +#include "../../DesktopEditor/raster/ImageFileFormatChecker.h" +#include "../../DesktopEditor/common/Directory.h" #include "../Src/Streams.h" #include "../Src/Utils.h" @@ -52,194 +62,28 @@ #include "../Src/FontCidTT.h" #include "../Src/Pattern.h" -#include +#define TEST_PDFWRITER_LIB -#include "../../DesktopEditor/raster/BgraFrame.h" -#include "../../DesktopEditor/common/File.h" +#if defined(_WIN64) + #pragma comment(lib, "../../build/bin/icu/win_64/icuuc.lib") +#elif defined (_WIN32) -#include "../../DesktopEditor/cximage/CxImage/ximage.h" -#include "../../DesktopEditor/cximage/CxImage/ximatif.h" -#include "../../DesktopEditor/raster/BgraFrame.h" - -#include "../../DesktopEditor/cximage/tiff/tiffio.h" - -#include "../../DesktopEditor/fontengine/ApplicationFonts.h" -#include "../../DesktopEditor/raster/Metafile/MetaFile.h" -#include -#include - -#include "../Src/FastStringToDouble.h" - -#ifdef DrawText -#undef DrawText + #if defined(_DEBUG) + #pragma comment(lib, "../../build/lib/win_32/DEBUG/graphics.lib") + #pragma comment(lib, "../../build/lib/win_32/DEBUG/kernel.lib") + //#pragma comment(lib, "../../build/lib/win_32/DEBUG/UnicodeConverter.lib") + #pragma comment(lib, "../../build/lib/win_32/DEBUG/CryptoPPLib.lib") + #else + #pragma comment(lib, "../../build/lib/win_32/graphics.lib") + #pragma comment(lib, "../../build/lib/win_32/kernel.lib") + //#pragma comment(lib, "../../build/lib/win_32/UnicodeConverter.lib") + #pragma comment(lib, "../../build/lib/win_32/CryptoPPLib.lib") + #endif + #pragma comment(lib, "../../build/bin/icu/win_32/icuuc.lib") #endif using namespace PdfWriter; -void TestStreams() -{ - CFileStream oFS; - oFS.OpenFile(L"D:/Test Files/1.txt", false); - - while (!oFS.IsEof()) - { - char nChar = oFS.ReadChar(); - std::cout << nChar; - } - - CMemoryStream oMS; - oMS.WriteStream(&oFS, 0, NULL); - - CFileStream oTS; - oTS.OpenFile(L"D:/Test Files/TestStreams.tmp", true); - oTS.WriteStream(&oMS, 0, NULL); - oTS.WriteChar(' '); - oTS.WriteChar('c'); - oTS.WriteChar(' '); - oTS.WriteBinary((const BYTE*)"123", 3, NULL); - oTS.WriteChar(' '); - oTS.WriteEscapeName((const char*)"EscapeName"); - oTS.WriteChar(' '); - oTS.WriteEscapeText((const BYTE*)"EscapeTest", StrLen("EscapeTest", 12)); - oTS.WriteChar(' '); - oTS.WriteHex(251, 2); - oTS.WriteChar(' '); - oTS.WriteHex(251, 4); - oTS.WriteChar(' '); - oTS.WriteInt(63); - oTS.WriteChar(' '); - oTS.WriteReal(0.12); - oTS.WriteChar(' '); - oTS.WriteStr("String"); - oTS.WriteChar(' '); - oTS.Close(); - - CFileStream oTS2; - oTS2.OpenFile(L"D:/Test Files/TestStreamsFilter.tmp", true); - oTS2.WriteStream(&oMS, STREAM_FILTER_FLATE_DECODE, NULL); - oTS2.Close(); -} -void TestObjects() -{ - CStream* pStream = new CFileStream(); - ((CFileStream*)pStream)->OpenFile(L"D:/Test Files/TestObjects.tmp", true); - - CNullObject oNull; - pStream->Write(&oNull); - pStream->WriteChar('\n'); - - CBoolObject oBool = true; - pStream->Write(&oBool); - pStream->WriteChar('\n'); - - CNumberObject oNumber = 75; - pStream->Write(&oNumber); - pStream->WriteChar('\n'); - - CRealObject oReal = 13.756; - pStream->Write(&oReal); - pStream->WriteChar('\n'); - - CNameObject oName = "Name"; - pStream->Write(&oName); - pStream->WriteChar('\n'); - - CStringObject oString("String"); - pStream->Write(&oString, NULL); - pStream->WriteChar('\n'); - - CBinaryObject oBinary((BYTE*)"123", 3); - pStream->Write(&oBinary, NULL); - pStream->WriteChar('\n'); - - CArrayObject* pArray = new CArrayObject(); - pArray->Add(12); - pArray->Add(0.13); - pArray->Add(13.1); - pStream->Write(pArray, NULL); - pStream->WriteChar('\n'); - - CProxyObject oProxy(pArray); - oProxy.SetRef(123, 0); - pStream->Write(&oProxy, NULL); - pStream->WriteChar('\n'); - - CDictObject oDict; - oDict.Add("Bool", true); - oDict.Add("Real", 0.12); - oDict.Add("Number", 12); - oDict.Add("Name", "SomeName"); - oDict.Add("Array", pArray); - pStream->Write(&oDict, NULL); - pStream->WriteChar('\n'); - - delete pStream; -} -void TestEncrypt() -{ - CEncrypt oEncrypt; - oEncrypt.Init(); - oEncrypt.InitKey(1231, 0); - - CFileStream oFS; - oFS.OpenFile(L"D:/Test Files/TestStreams.tmp", false); - - CFileStream oTS; - oTS.OpenFile(L"D:/Test Files/TestEncrypt.tmp", true); - oTS.WriteStream(&oFS, 0, &oEncrypt); - oTS.Close(); - - oFS.Close(); -} -void TestDict() -{ - CStream* pStream = new CFileStream(); - ((CFileStream*)pStream)->OpenFile(L"D:/Test Files/TestDict.tmp", true); - - CXref oXref(0); - - CDictObject* pDict = new CDictObject(&oXref); - pDict->Add("Bool", true); - pDict->Add("Real", 0.12); - pDict->Add("Number", 12); - pDict->Add("Name", "SomeName"); - pDict->Add("Array", new CArrayObject()); - - CStream* pDictStream = pDict->GetStream(); - pDictStream->WriteEscapeText((BYTE*)"TestTest", 8); - pDictStream->WriteBinary((BYTE*)"TestTest", 8, NULL); - - CDictObject* pDict2 = new CDictObject(&oXref); - pDict2->Add("Bool", true); - pDict2->Add("Real", 0.12); - pDict2->Add("Number", 12); - pDict2->Add("Name", "SomeName"); - pDict2->Add("Array", new CArrayObject()); - - pDict2->SetFilter(STREAM_FILTER_FLATE_DECODE); - - CStream* pDictStream2 = pDict2->GetStream(); - pDictStream2->WriteEscapeText((BYTE*)"TestTest", 8); - pDictStream2->WriteBinary((BYTE*)"TestTest", 8, NULL); - - TDate oDate; - MemSet(&oDate, 0, sizeof(oDate)); - oDate.nDay = 18; - oDate.nMonth = 10; - oDate.nYear = 1986; - oDate.nHour = 12; - oDate.nMinutes = 0; - oDate.nSeconds = 0; - oDate.nInd = '-'; - - CInfoDict* pInfo = new CInfoDict(&oXref); - pInfo->SetInfo(EInfoType::InfoCreator, "Ilya"); - pInfo->SetInfo(EInfoType::InfoCreationDate, oDate); - - oXref.WriteToStream(pStream, NULL); - - delete pStream; -} void TestDocument1() { // PageLabels and Encryption @@ -251,11 +95,9 @@ void TestDocument1() oPdf.AddPage(); oPdf.AddPageLabel(2, pagenumstyle_UpperRoman, 21, "UppRom-"); - oPdf.SetPassword("123", "qwe"); - oPdf.SetPermission(ENABLE_READ); - oPdf.SetEncryptionMode(encryptmode_R3); + oPdf.SetPasswords(L"123", L"qwe"); - oPdf.SaveToFile(L"D:/Test Files/Test1.pdf"); + oPdf.SaveToFile(L"D:/test/_pdf/Test1.pdf"); oPdf.Close(); } void TestDocument2() @@ -287,7 +129,7 @@ void TestDocument2() pOutline11->SetDestination(pDest); - oPdf.SaveToFile(L"D:/Test Files/Test2.pdf"); + oPdf.SaveToFile(L"D:/test/_pdf/Test2.pdf"); oPdf.Close(); } void TestDocument3() @@ -456,7 +298,7 @@ void TestDocument3() - oPdf.SaveToFile(L"D:/Test Files/Test3.pdf"); + oPdf.SaveToFile(L"D:/test/_pdf/Test3.pdf"); oPdf.Close(); } void TestDocument4() @@ -476,7 +318,7 @@ void TestDocument4() CAnnotation* pAnnot = oPdf.CreateLinkAnnot(0, TRect(0, 100, 100, 0), pDest); pAnnot = oPdf.CreateUriLinkAnnot(0, TRect(0, 200, 100, 100), "www.rbc.ru"); - oPdf.SaveToFile(L"D:/Test Files/Test4.pdf"); + oPdf.SaveToFile(L"D:/test/_pdf/Test4.pdf"); oPdf.Close(); } void TestDocument5() @@ -488,9 +330,9 @@ void TestDocument5() pPage->SetWidth(600); //CBgraFrame oFrame; - //oFrame.OpenFile(L"D:/Test Files/Test.jb2"); + //oFrame.OpenFile(L"D:/test/_pdf/Test.jb2"); - //TIFF* pTiff = TIFFOpenW(L"D:/Test Files/Test.tiff", "w+"); + //TIFF* pTiff = TIFFOpenW(L"D:/test/_pdf/Test.tiff", "w+"); //TIFFSetField(pTiff, TIFFTAG_IMAGEWIDTH, 800); //TIFFSetField(pTiff, TIFFTAG_IMAGELENGTH, 1000); //TIFFSetField(pTiff, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT); @@ -511,7 +353,7 @@ void TestDocument5() //TIFFClose(pTiff); //CImageDict* pImage = oPdf.CreateImage(); - //pImage->LoadCCITT4(L"D:/Test Files/Test.tiff", 800, 1000); + //pImage->LoadCCITT4(L"D:/test/_pdf/Test.tiff", 800, 1000); //pPage->DrawImage(pImage, 100, 100, 200, 200); BYTE* pBuffer = new BYTE[100 * 800]; @@ -544,14 +386,14 @@ void TestDocument5() //CxImage oImage; - //oImage.Load(L"D:/Test Files/Test.jb2"); + //oImage.Load(L"D:/test/_pdf/Test.jb2"); //CImageDict* pJb2Image = oPdf.CreateImage(); - //pJb2Image->LoadJb2(L"D:/Test Files/Test.jb2", 1728, 2376); + //pJb2Image->LoadJb2(L"D:/test/_pdf/Test.jb2", 1728, 2376); //pPage->DrawImage(pJb2Image, 100, 100, 200, 200); //CImageDict* pJpegImage = oPdf.CreateImage(); - //pJpegImage->LoadJpeg(L"D:/Test Files/Test.jpg", 670, 473); + //pJpegImage->LoadJpeg(L"D:/test/_pdf/Test.jpg", 670, 473); //pPage->DrawImage(pJpegImage, 100, 100, 200, 200); //BYTE* pAlpha = new BYTE[4 * 400 * 300]; @@ -579,14 +421,14 @@ void TestDocument5() //} //CImageDict* pJpxImage = oPdf.CreateImage(); - //pJpxImage->LoadJpx(L"D:/Test Files/Test.jp2", 400, 300); + //pJpxImage->LoadJpx(L"D:/test/_pdf/Test.jp2", 400, 300); //pJpxImage->LoadSMask(pAlpha, 400, 300); //pPage->DrawImage(pJpxImage, 300, 100, 200, 200); //delete[] pAlpha; ////CImageDict* pJb2Image = oPdf.CreateImage(); - ////pJb2Image->LoadJb2(L"D:/Test Files/Test.jbig2", 400, 300); + ////pJb2Image->LoadJb2(L"D:/test/_pdf/Test.jbig2", 400, 300); ////pPage->DrawImage(pJb2Image, 300, 300, 200, 200); //CImageDict* pRawImage = oPdf.CreateImage(); @@ -620,7 +462,7 @@ void TestDocument5() //pPage->DrawImage(pRawImage, 300, 300, 200, 200); //delete[] pBgra; - oPdf.SaveToFile(L"D:/Test Files/Test5.pdf"); + oPdf.SaveToFile(L"D:/test/_pdf/Test5.pdf"); oPdf.Close(); } void TestDocument6() @@ -693,7 +535,7 @@ void TestDocument6() pPage->ClosePath(); pPage->Fill(); - oPdf.SaveToFile(L"D:/Test Files/Test6.pdf"); + oPdf.SaveToFile(L"D:/test/_pdf/Test6.pdf"); oPdf.Close(); } void TestDocument7() @@ -726,8 +568,8 @@ void TestDocument7() pPage->SetHeight(600); pPage->SetWidth(1000); - //CFontCidTrueType* pFont = oPdf.CreateTrueTypeFont(L"D:/Test Files/Test.ttf", 0); - CFontCidTrueType* pFont = oPdf.CreateTrueTypeFont(L"D:/Test Files/cambria.ttc", 1); + //CFontCidTrueType* pFont = oPdf.CreateTrueTypeFont(L"D:/test/_pdf/Test.ttf", 0); + CFontCidTrueType* pFont = oPdf.CreateTrueTypeFont(L"D:/test/_pdf/cambria.ttc", 1); pPage->BeginText(); @@ -758,7 +600,7 @@ void TestDocument7() pPage->EndText(); - oPdf.SaveToFile(L"D:/Test Files/Test7.pdf"); + oPdf.SaveToFile(L"D:/test/_pdf/Test7.pdf"); oPdf.Close(); } void TestDocument8() @@ -837,7 +679,7 @@ void TestDocument8() pPage->GrRestore(); - oPdf.SaveToFile(L"D:/Test Files/Test8.pdf"); + oPdf.SaveToFile(L"D:/test/_pdf/Test8.pdf"); oPdf.Close(); } void TestDocument9() @@ -853,7 +695,7 @@ void TestDocument9() pPage->SetWidth(600); CImageDict* pJpegImage = oPdf.CreateImage(); - pJpegImage->LoadJpeg(L"D:/Test Files/Test.jpg", 600, 400); + pJpegImage->LoadJpeg(L"D:/test/_pdf/Test.jpg", 600, 400); CImageTilePattern* pPattern = oPdf.CreateImageTilePattern(70, 70, pJpegImage, NULL, imagetilepatterntype_InverseX); @@ -865,63 +707,38 @@ void TestDocument9() pPage->GrRestore(); - oPdf.SaveToFile(L"D:/Test Files/Test9.pdf"); + oPdf.SaveToFile(L"D:/test/_pdf/Test9.pdf"); oPdf.Close(); } -std::vector GetAllFilesInFolder(std::wstring wsFolder, std::wstring wsExt) + +void ConvertFolder(std::wstring wsFolderPath) { - std::vector vwsNames; + NSFonts::IApplicationFonts *pAppFonts = NSFonts::NSApplication::Create(); + pAppFonts->Initialize(); - std::wstring wsSearchPath = wsFolder; - wsSearchPath.append(L"*."); - wsSearchPath.append(wsExt); + MetaFile::IMetaFile *pMetaFile = MetaFile::Create(pAppFonts); - WIN32_FIND_DATA oFindData; - HANDLE hFind = ::FindFirstFile(wsSearchPath.c_str(), &oFindData); - if (hFind != INVALID_HANDLE_VALUE) - { - do - { - if (!(oFindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) - { - vwsNames.push_back(oFindData.cFileName); - } - } while (::FindNextFile(hFind, &oFindData)); - ::FindClose(hFind); - } - return vwsNames; -} -void ConvertFolder(std::wstring wsFolderPath, const int nType) -{ - CApplicationFonts oFonts; - oFonts.Initialize(); - - MetaFile::CMetaFile oMetaFile(&oFonts); - CPdfRenderer oRenderer(&oFonts); + CPdfRenderer oRenderer(pAppFonts); - oMetaFile.Close(); + pMetaFile->Close(); std::wstring sExt; - switch (nType) - { - case MetaFile::c_lMetaEmf: sExt = L"emf"; break; - case MetaFile::c_lMetaWmf: sExt = L"wmf"; break; - case MetaFile::c_lMetaSvm: sExt = L"svm"; break; - } double dPx2Mm = 25.4 / 96; - std::vector vFiles = GetAllFilesInFolder(wsFolderPath, sExt); + + std::vector vFiles = NSDirectory::GetFiles(wsFolderPath); + for (int nIndex = 0; nIndex < vFiles.size(); nIndex++) { oRenderer.NewPage(); std::wstring wsFilePath = wsFolderPath; wsFilePath.append(vFiles.at(nIndex)); - if (oMetaFile.LoadFromFile(wsFilePath.c_str())) + if (pMetaFile->LoadFromFile(wsFilePath.c_str())) { double dW, dH, dX, dY; - oMetaFile.GetBounds(&dX, &dY, &dW, &dH); + pMetaFile->GetBounds(&dX, &dY, &dW, &dH); dW *= dPx2Mm; dH *= dPx2Mm; @@ -934,163 +751,56 @@ void ConvertFolder(std::wstring wsFolderPath, const int nType) oRenderer.put_Width(dW); oRenderer.put_Height(dH); - //oMetaFile.DrawOnRenderer(&oRenderer, -dX, -dY, dW, dH); - oMetaFile.DrawOnRenderer(&oRenderer, 0, 0, dW, dH); - oMetaFile.Close(); + //pMetaFile->DrawOnRenderer(&oRenderer, -dX, -dY, dW, dH); + pMetaFile->DrawOnRenderer(&oRenderer, 0, 0, dW, dH); + pMetaFile->Close(); } printf("%d of %d %S\n", nIndex, vFiles.size(), vFiles.at(nIndex).c_str()); } oRenderer.SaveToFile(wsFolderPath + L"Out.pdf"); + + delete pMetaFile; + delete pAppFonts; } -void TestMetafile() + +//void TestOnlineBin() +//{ +// std::wstring wsFolderPath = L"D://Test Files//Txt//Gradient//"; +// //std::wstring wsFolderPath = L"D://Test Files//Txt//Text//"; +// std::wstring wsTempFolder = L"D://Test Files//Temp//"; +// +// CApplicationFonts oFonts; +// oFonts.Initialize(); +// +// clock_t oBeginTime = clock(); +// double dPx2Mm = 25.4 / 96; +// std::vector vFiles = GetAllFilesInFolder(wsFolderPath, L"txt"); +// for (int nIndex = 0; nIndex < vFiles.size(); nIndex++) +// { +// std::wstring wsFilePath = wsFolderPath; +// wsFilePath.append(vFiles.at(nIndex)); +// std::wstring wsOutPath = wsFolderPath + L"Out.pdf"; +// +// CPdfRenderer oRenderer(&oFonts); +// oRenderer.SetTempFolder(wsTempFolder); +// oRenderer.OnlineWordToPdf(wsFilePath, wsOutPath); +// +// printf("%d of %d %S\n", nIndex, vFiles.size(), vFiles.at(nIndex).c_str()); +// } +// +// clock_t oEndTime = clock(); +// double dElapsedSecs = double(oEndTime - oBeginTime) / CLOCKS_PER_SEC; +// printf("%f\n", dElapsedSecs); +//} +// +int _tmain(int argc, _TCHAR* argv[]) { - ConvertFolder(L"D://Test Files//Emf//", MetaFile::c_lMetaEmf); - //ConvertFolder(L"D://Test Files//Wmf//", MetaFile::c_lMetaWmf); -} -void TestOnlineBin() -{ - std::wstring wsFolderPath = L"D://Test Files//Txt//Gradient//"; - //std::wstring wsFolderPath = L"D://Test Files//Txt//Text//"; - std::wstring wsTempFolder = L"D://Test Files//Temp//"; - CApplicationFonts oFonts; - oFonts.Initialize(); + TestDocument1(); - clock_t oBeginTime = clock(); - double dPx2Mm = 25.4 / 96; - std::vector vFiles = GetAllFilesInFolder(wsFolderPath, L"txt"); - for (int nIndex = 0; nIndex < vFiles.size(); nIndex++) - { - std::wstring wsFilePath = wsFolderPath; - wsFilePath.append(vFiles.at(nIndex)); - std::wstring wsOutPath = wsFolderPath + L"Out.pdf"; - CPdfRenderer oRenderer(&oFonts); - oRenderer.SetTempFolder(wsTempFolder); - oRenderer.OnlineWordToPdf(wsFilePath, wsOutPath); - - printf("%d of %d %S\n", nIndex, vFiles.size(), vFiles.at(nIndex).c_str()); - } - - clock_t oEndTime = clock(); - double dElapsedSecs = double(oEndTime - oBeginTime) / CLOCKS_PER_SEC; - printf("%f\n", dElapsedSecs); + return S_OK; } -void TestDouble() -{ - const int nMaxInt = NSFastIntToString::c_nMaxInt; - const int nCount = 100000; - double pDoubles[nCount]; - for (int nIndex = 0; nIndex < nCount; nIndex++) - { - pDoubles[nIndex] = (rand() % (nMaxInt - 1) + (rand() % (nMaxInt - 1)) / (double)nMaxInt); - } - pDoubles[0] = 120.0012; - pDoubles[1] = 12.012312; - pDoubles[2] = 0.00012312; - - clock_t oBeginTime = clock(); - - char pBuffer[32]; - for (int nI = 0; nI < 10; nI++) - { - for (int nIndex = 0; nIndex < nCount; nIndex++) - { - double dValue = pDoubles[nIndex]; - memset(pBuffer, 0x00, 32); - FtoA(pBuffer, dValue, pBuffer + 31); - } - } - - clock_t oEndTime = clock(); - double dElapsedSecs = double(oEndTime - oBeginTime) / CLOCKS_PER_SEC; - printf("FtoA %f\n", dElapsedSecs); - - oBeginTime = clock(); - - for (int nI = 0; nI < 10; nI++) - { - - for (int nIndex = 0; nIndex < nCount; nIndex++) - { - int nResLen = 0; - double dValue = pDoubles[nIndex]; - int nIVal = (int)dValue; - int nFVal = (int)(fabs(dValue - nIVal) * 10000); - - int nLen = 0; - const char* sString = NSFastIntToString::GetString(abs(nIVal), nLen); - if (nIVal < 0) - pBuffer[nResLen++] = '-'; - - memcpy(pBuffer + nResLen, sString, nLen); - nResLen += nLen; - - if (nFVal) - { - sString = NSFastIntToString::GetString(nFVal, nLen); - - pBuffer[nResLen++] = '.'; - int nZeros = 4 - nLen; - if (nZeros > 0) - { - memcpy(pBuffer + nResLen, NSFastIntToString::GetZeros(nZeros), nLen); - nResLen += nZeros; - } - - memcpy(pBuffer + nResLen, sString, nLen); - } - } - } - - oEndTime = clock(); - dElapsedSecs = double(oEndTime - oBeginTime) / CLOCKS_PER_SEC; - printf("Fast %f\n", dElapsedSecs); -} - -void main() -{ - //TestStreams(); - //TestObjects(); - //TestEncrypt(); - //TestDict(); - //TestDocument1(); - //TestDocument2(); - //TestDocument3(); - //TestDocument4(); - //TestDocument5(); - //TestDocument6(); - //TestDocument7(); - //TestDocument8(); - //TestDocument9(); - //TestMetafile(); - TestOnlineBin(); - //TestDouble(); - - //std::string wsTest = ""; - - //wsTest = "static const char c_nPrecisionLen[] = {"; - - //int nMax = 100000; - //for (int nIndex = 0; nIndex < nMax; nIndex++) - //{ - - // std::string sInt = std::to_string(nIndex); - // while (sInt.length() > 1 && '0' == sInt.at(sInt.length() - 1)) - // sInt.pop_back(); - - // wsTest += std::to_string(sInt.length()); - - // if (nIndex != nMax - 1) - // wsTest += ","; - //} - - //wsTest += "};"; - - - char q; - std::cin >> q; -} diff --git a/PdfWriter/Src/Document.cpp b/PdfWriter/Src/Document.cpp index e5373e2f7e..265f2c0d6d 100644 --- a/PdfWriter/Src/Document.cpp +++ b/PdfWriter/Src/Document.cpp @@ -81,7 +81,7 @@ namespace PdfWriter { Close(); } - bool CDocument::CreateNew() + bool CDocument::CreateNew() { Close(); @@ -109,7 +109,7 @@ namespace PdfWriter return false; m_pInfo->SetCreationTime(); - m_pInfo->SetInfo(InfoProducer, "Ascensio System SIA Copyright (c) 2015"); + m_pInfo->SetInfo(InfoProducer, "Ascensio System SIA Copyright (c) 2018"); m_nCurPageNum = -1; @@ -122,7 +122,7 @@ namespace PdfWriter return true; } - void CDocument::Close() + void CDocument::Close() { // Все объекты удаляются внутри CXref RELEASEOBJECT(m_pXref); @@ -151,11 +151,13 @@ namespace PdfWriter m_vFreeTypeFonts.clear(); if (m_pFreeTypeLibrary) { +#ifndef TEST_PDFWRITER_LIB FT_Done_FreeType(m_pFreeTypeLibrary); m_pFreeTypeLibrary = NULL; +#endif } } - bool CDocument::SaveToFile(const std::wstring& wsPath) + bool CDocument::SaveToFile(const std::wstring& wsPath) { CFileStream* pStream = new CFileStream(); if (!pStream || !pStream->OpenFile(wsPath, true)) @@ -169,7 +171,7 @@ namespace PdfWriter return true; } - void CDocument::SaveToStream(CStream* pStream) + void CDocument::SaveToStream(CStream* pStream) { unsigned long nRet = OK; @@ -190,7 +192,7 @@ namespace PdfWriter m_pXref->WriteToStream(pStream, pEncrypt); } - void CDocument::PrepareEncryption() + void CDocument::PrepareEncryption() { CEncrypt* pEncrypt = m_pEncryptDict->GetEncrypt(); if (!pEncrypt) @@ -207,18 +209,10 @@ namespace PdfWriter else pID->Clear(); - pID->Add(new CBinaryObject(pEncrypt->m_anEncryptID, ID_LEN)); - pID->Add(new CBinaryObject(pEncrypt->m_anEncryptID, ID_LEN)); + pID->Add(new CBinaryObject(pEncrypt->m_anEncryptID, 16)); + pID->Add(new CBinaryObject(pEncrypt->m_anEncryptID, 16)); } - void CDocument::SetEncryptionMode(EEncryptMode eMode, unsigned int unKeyLen) - { - if (!m_bEncrypt) - return; - - CEncrypt* pEncrypt = m_pEncryptDict->GetEncrypt(); - pEncrypt->SetMode(eMode, unKeyLen); - } - void CDocument::SetPassword(const char* sOwnerPassword, const char* sUserPassword) + void CDocument::SetPasswords(const std::wstring & wsOwnerPassword, const std::wstring & wsUserPassword) { if (!m_pEncryptDict) m_pEncryptDict = new CEncryptDict(m_pXref); @@ -226,11 +220,12 @@ namespace PdfWriter if (!m_pEncryptDict) return; - m_pEncryptDict->SetPassword(sOwnerPassword, sUserPassword); - m_pTrailer->Add("Encrypt", m_pEncryptDict); + m_pEncryptDict->SetPasswords(wsOwnerPassword, wsUserPassword); + + m_pTrailer->Add("Encrypt", m_pEncryptDict); m_bEncrypt = true; } - CPage* CDocument::AddPage() + CPage* CDocument::AddPage() { CPage* pPage = new CPage(m_pXref, m_pPageTree, this); m_pPageTree->AddPage(pPage); @@ -246,7 +241,7 @@ namespace PdfWriter m_nCurPageNum++; return pPage; } - void CDocument::SetPermission(unsigned int unPermission) + void CDocument::SetPermission(unsigned int unPermission) { if (!m_bEncrypt) return; @@ -254,11 +249,11 @@ namespace PdfWriter CEncrypt* pEncrypt = m_pEncryptDict->GetEncrypt(); pEncrypt->SetPermission(unPermission); } - void CDocument::SetCompressionMode(unsigned int unMode) + void CDocument::SetCompressionMode(unsigned int unMode) { m_unCompressMode = unMode; } - void CDocument::AddPageLabel(EPageNumStyle eStyle, unsigned int unFirstPage, const char* sPrefix) + void CDocument::AddPageLabel(EPageNumStyle eStyle, unsigned int unFirstPage, const char* sPrefix) { CDictObject* pPageLabel = CreatePageLabel(eStyle, unFirstPage, sPrefix); if (!pPageLabel) @@ -266,7 +261,7 @@ namespace PdfWriter m_pCatalog->AddPageLabel(m_nCurPageNum, pPageLabel); } - void CDocument::AddPageLabel(unsigned int unPageNum, EPageNumStyle eStyle, unsigned int unFirstPage, const char* sPrefix) + void CDocument::AddPageLabel(unsigned int unPageNum, EPageNumStyle eStyle, unsigned int unFirstPage, const char* sPrefix) { CDictObject* pPageLabel = CreatePageLabel(eStyle, unFirstPage, sPrefix); if (!pPageLabel) @@ -274,7 +269,7 @@ namespace PdfWriter m_pCatalog->AddPageLabel(unPageNum, pPageLabel); } - CDictObject* CDocument::CreatePageLabel(EPageNumStyle eStyle, unsigned int unFirstPage, const char* sPrefix) + CDictObject* CDocument::CreatePageLabel(EPageNumStyle eStyle, unsigned int unFirstPage, const char* sPrefix) { CDictObject* pLabel = new CDictObject(); if (!pLabel) @@ -298,7 +293,7 @@ namespace PdfWriter return pLabel; } - COutline* CDocument::CreateOutline(COutline* pParent, const char* sTitle) + COutline* CDocument::CreateOutline(COutline* pParent, const char* sTitle) { if (!pParent) { @@ -316,7 +311,7 @@ namespace PdfWriter return new COutline(pParent, sTitle, m_pXref); } - CDestination* CDocument::CreateDestination(unsigned int unPageIndex) + CDestination* CDocument::CreateDestination(unsigned int unPageIndex) { if (unPageIndex >= m_vPages.size()) return NULL; @@ -324,7 +319,7 @@ namespace PdfWriter CPage* pPage = m_vPages.at(unPageIndex); return new CDestination(pPage, m_pXref); } - CExtGrState* CDocument::FindExtGrState(double dAlphaStroke, double dAlphaFill, EBlendMode eMode, int nStrokeAdjustment) + CExtGrState* CDocument::FindExtGrState(double dAlphaStroke, double dAlphaFill, EBlendMode eMode, int nStrokeAdjustment) { CExtGrState* pExtGrState = NULL; for (unsigned int unIndex = 0, unCount = m_vExtGrStates.size(); unIndex < unCount; unIndex++) @@ -348,7 +343,7 @@ namespace PdfWriter return NULL; } - CExtGrState* CDocument::GetExtGState(double dAlphaStroke, double dAlphaFill, EBlendMode eMode, int nStrokeAdjustment) + CExtGrState* CDocument::GetExtGState(double dAlphaStroke, double dAlphaFill, EBlendMode eMode, int nStrokeAdjustment) { CExtGrState* pExtGrState = FindExtGrState(dAlphaStroke, dAlphaFill, eMode, nStrokeAdjustment); @@ -376,7 +371,7 @@ namespace PdfWriter return pExtGrState; } - CExtGrState* CDocument::GetStrokeAlpha(double dAlpha) + CExtGrState* CDocument::GetStrokeAlpha(double dAlpha) { CExtGrState* pExtGrState = NULL; for (unsigned int unIndex = 0, unCount = m_vStrokeAlpha.size(); unIndex < unCount; unIndex++) @@ -395,7 +390,7 @@ namespace PdfWriter m_vStrokeAlpha.push_back(pExtGrState); return pExtGrState; } - CExtGrState* CDocument::GetFillAlpha(double dAlpha) + CExtGrState* CDocument::GetFillAlpha(double dAlpha) { CExtGrState* pExtGrState = NULL; for (unsigned int unIndex = 0, unCount = m_vFillAlpha.size(); unIndex < unCount; unIndex++) @@ -414,7 +409,7 @@ namespace PdfWriter m_vFillAlpha.push_back(pExtGrState); return pExtGrState; } - CAnnotation* CDocument::CreateTextAnnot(unsigned int unPageNum, TRect oRect, const char* sText) + CAnnotation* CDocument::CreateTextAnnot(unsigned int unPageNum, TRect oRect, const char* sText) { CAnnotation* pAnnot = new CTextAnnotation(m_pXref, oRect, sText); if (pAnnot) @@ -425,7 +420,7 @@ namespace PdfWriter return pAnnot; } - CAnnotation* CDocument::CreateLinkAnnot(unsigned int unPageNum, TRect oRect, CDestination* pDest) + CAnnotation* CDocument::CreateLinkAnnot(unsigned int unPageNum, TRect oRect, CDestination* pDest) { CAnnotation* pAnnot = new CLinkAnnotation(m_pXref, oRect, pDest); @@ -437,7 +432,7 @@ namespace PdfWriter return pAnnot; } - CAnnotation* CDocument::CreateUriLinkAnnot(unsigned int unPageNum, TRect oRect, const char* sUri) + CAnnotation* CDocument::CreateUriLinkAnnot(unsigned int unPageNum, TRect oRect, const char* sUri) { CAnnotation* pAnnot = new CUriLinkAnnotation(m_pXref, oRect, sUri); @@ -449,11 +444,11 @@ namespace PdfWriter return pAnnot; } - CImageDict* CDocument::CreateImage() + CImageDict* CDocument::CreateImage() { return new CImageDict(m_pXref, this); } - CFont14* CDocument::CreateFont14(EStandard14Fonts eType) + CFont14* CDocument::CreateFont14(EStandard14Fonts eType) { return new CFont14(m_pXref, this, eType); } @@ -473,7 +468,7 @@ namespace PdfWriter m_vTTFonts.push_back(TFontInfo(wsFontPath, unIndex, pFont)); return pFont; } - char* CDocument::GetTTFontTag() + char* CDocument::GetTTFontTag() { if (0 == m_sTTFontTag[0]) { @@ -493,7 +488,7 @@ namespace PdfWriter return m_sTTFontTag; } - void CDocument::AddFreeTypeFont(CFontCidTrueType* pFont) + void CDocument::AddFreeTypeFont(CFontCidTrueType* pFont) { for (int nIndex = 0, nCount = m_vFreeTypeFonts.size(); nIndex < nCount; nIndex++) { @@ -521,14 +516,15 @@ namespace PdfWriter m_vFreeTypeFonts.erase(m_vFreeTypeFonts.begin() + MAX_OPENED_FT_FACES, m_vFreeTypeFonts.end()); } } - FT_Library CDocument::GetFreeTypeLibrary() + FT_Library CDocument::GetFreeTypeLibrary() { +#ifndef TEST_PDFWRITER_LIB if (!m_pFreeTypeLibrary) FT_Init_FreeType(&m_pFreeTypeLibrary); - +#endif return m_pFreeTypeLibrary; } - CJbig2Global* CDocument::GetJbig2Global() + CJbig2Global* CDocument::GetJbig2Global() { if (m_pJbig2 && m_pJbig2->GetImagesCount() > 4) { @@ -542,7 +538,7 @@ namespace PdfWriter return m_pJbig2; } - CShading* CDocument::CreateShading(CPage* pPage, double *pPattern, bool bAxial, unsigned char* pColors, unsigned char* pAlphas, double* pPoints, int nCount, CExtGrState*& pExtGrState) + CShading* CDocument::CreateShading(CPage* pPage, double *pPattern, bool bAxial, unsigned char* pColors, unsigned char* pAlphas, double* pPoints, int nCount, CExtGrState*& pExtGrState) { pExtGrState = NULL; @@ -632,7 +628,7 @@ namespace PdfWriter return pColorShading; } - CShading* CDocument::CreateAxialShading(double dX0, double dY0, double dX1, double dY1, unsigned char* pColors, double* pPoints, int nCount) + CShading* CDocument::CreateAxialShading(double dX0, double dY0, double dX1, double dY1, unsigned char* pColors, double* pPoints, int nCount) { for (int nIndex = 0, nShadingsCount = m_vShadings.size(); nIndex < nShadingsCount; nIndex++) { @@ -655,7 +651,7 @@ namespace PdfWriter return pShading; } - CShading* CDocument::CreateRadialShading(double dX0, double dY0, double dR0, double dX1, double dY1, double dR1, unsigned char* pColors, double* pPoints, int nCount) + CShading* CDocument::CreateRadialShading(double dX0, double dY0, double dR0, double dX1, double dY1, double dR1, unsigned char* pColors, double* pPoints, int nCount) { for (int nIndex = 0, nShadingsCount = m_vShadings.size(); nIndex < nShadingsCount; nIndex++) { @@ -710,12 +706,12 @@ namespace PdfWriter return CreateImageTilePattern(dW, dH, pImage, NULL, imagetilepatterntype_Default); } - CShading* CDocument::CreateAxialShading(CPage* pPage, double dX0, double dY0, double dX1, double dY1, unsigned char* pColors, unsigned char* pAlphas, double* pPoints, int nCount, CExtGrState*& pExtGrState) + CShading* CDocument::CreateAxialShading(CPage* pPage, double dX0, double dY0, double dX1, double dY1, unsigned char* pColors, unsigned char* pAlphas, double* pPoints, int nCount, CExtGrState*& pExtGrState) { double pPattern[] ={ dX0, dY0, dX1, dY1 }; return CreateShading(pPage, pPattern, true, pColors, pAlphas, pPoints, nCount, pExtGrState); } - CShading* CDocument::CreateRadialShading(CPage* pPage, double dX0, double dY0, double dR0, double dX1, double dY1, double dR1, unsigned char* pColors, unsigned char* pAlphas, double* pPoints, int nCount, CExtGrState*& pExtGrState) + CShading* CDocument::CreateRadialShading(CPage* pPage, double dX0, double dY0, double dR0, double dX1, double dY1, double dR1, unsigned char* pColors, unsigned char* pAlphas, double* pPoints, int nCount, CExtGrState*& pExtGrState) { double pPattern[] ={ dX0, dY0, dR0, dX1, dY1, dR1 }; return CreateShading(pPage, pPattern, false, pColors, pAlphas, pPoints, nCount, pExtGrState); diff --git a/PdfWriter/Src/Document.h b/PdfWriter/Src/Document.h index ca12faf6df..9e70b84bc1 100644 --- a/PdfWriter/Src/Document.h +++ b/PdfWriter/Src/Document.h @@ -90,8 +90,7 @@ namespace PdfWriter void Close(); bool SaveToFile(const std::wstring& wsPath); - void SetEncryptionMode(EEncryptMode eMode, unsigned int unKeyLen = 0); - void SetPassword(const char* sOwnerPassword, const char* sUserPassword); + void SetPasswords(const std::wstring & wsOwnerPassword, const std::wstring & wsUserPassword); void SetPermission(unsigned int unPermission); void SetCompressionMode(unsigned int unMode); diff --git a/PdfWriter/Src/Encrypt.cpp b/PdfWriter/Src/Encrypt.cpp index 4ddfab98db..13d1be69a7 100644 --- a/PdfWriter/Src/Encrypt.cpp +++ b/PdfWriter/Src/Encrypt.cpp @@ -32,486 +32,296 @@ #include "Encrypt.h" #include "Objects.h" -// Оптимизационные функции. -#define OptFunc1(x, y, z) (z ^ (x & (y ^ z))) -#define OptFunc2(x, y, z) OptFunc1(z, x, y) -#define OptFunc3(x, y, z) (x ^ y ^ z) -#define OptFunc4(x, y, z) (y ^ (x | ~z)) - -// Основной шаг в алгоритме MD5. -#define MD5STEP(f, w, x, y, z, data, s) \ - ( w += f(x, y, z) + data, w = w<>(32-s), w += x ) +#include "../../Common/3dParty/cryptopp/modes.h" +#include "../../Common/3dParty/cryptopp/aes.h" +#include "../../Common/3dParty/cryptopp/sha.h" +#include "../../Common/3dParty/cryptopp/filters.h" +#include "../../Common/3dParty/cryptopp/osrng.h" namespace PdfWriter { - static const BYTE c_sPaddingString[] = - { - 0x28, 0xBF, 0x4E, 0x5E, 0x4E, 0x75, 0x8A, 0x41, - 0x64, 0x00, 0x4E, 0x56, 0xFF, 0xFA, 0x01, 0x08, - 0x2E, 0x2E, 0x00, 0xB6, 0xD0, 0x68, 0x3E, 0x80, - 0x2F, 0x0C, 0xA9, 0xFE, 0x64, 0x53, 0x69, 0x7A - }; + static int SHA(int type, unsigned char *sMessage, int nMessageLen, unsigned char *sDigest) + { + int res = 0; + switch(type) + { + case 0: + case 256: + { + CryptoPP::SHA256 hash; + hash.Update( sMessage, nMessageLen > 0 ? nMessageLen : hash.DigestSize()); - void PadOrTrancatePassword(const char* sPassword, BYTE* pNewPassword) - { - unsigned int unLen = StrLen(sPassword, PASSWD_LEN + 1); - MemSet(pNewPassword, 0x00, PASSWD_LEN); + CryptoPP::SecByteBlock buffer(res = hash.DigestSize()); + hash.Final(buffer); - if (unLen >= PASSWD_LEN) - MemCpy(pNewPassword, (BYTE*)sPassword, PASSWD_LEN); - else + memcpy(sDigest, buffer.data(), buffer.size()); + }break; + case 1: + case 384: + { + CryptoPP::SHA384 hash; + hash.Update( sMessage, nMessageLen > 0 ? nMessageLen : hash.DigestSize()); + + CryptoPP::SecByteBlock buffer(res = hash.DigestSize()); + hash.Final(buffer); + + memcpy(sDigest, buffer.data(), buffer.size()); + }break; + case 2: + case 512: + { + CryptoPP::SHA512 hash; + hash.Update( sMessage, nMessageLen > 0 ? nMessageLen : hash.DigestSize()); + + CryptoPP::SecByteBlock buffer(res = hash.DigestSize()); + hash.Final(buffer); + + memcpy(sDigest, buffer.data(), buffer.size()); + }break; + } + return res; + } + + class CEncrypt::Impl + { + public: + Impl() : streamEncryption(NULL), aesEncryption(NULL) { - if (unLen > 0) - MemCpy(pNewPassword, (BYTE*)sPassword, unLen); - - MemCpy(pNewPassword + unLen, c_sPaddingString, PASSWD_LEN - unLen); + MemSet(m_anEncryptionKey, 0, 32); } - } - // The core of the MD5 algorithm, this alters an existing MD5 hash to - // reflect the addition of 16 longwords of new data. MD5Update blocks - // the data and converts bytes into longwords for this routine. - static void MD5ByteReverse(BYTE *pBuf, unsigned int nLongs) - { - unsigned int nTemp = 0; - do - { - nTemp = (unsigned int)((unsigned int)pBuf[3] << 8 | pBuf[2]) << 16 | ((unsigned int)pBuf[1] << 8 | pBuf[0]); - *(unsigned int *)pBuf = nTemp; - pBuf += 4; - } while (--nLongs); - } - static void MD5Transform(unsigned int anBuf[4], const unsigned int anIn[16]) - { - register unsigned int a, b, c, d; + virtual ~Impl() + { + if (streamEncryption) + delete streamEncryption; + if (aesEncryption) + delete aesEncryption; + } + void Reset() + { + unsigned char empty[16] = {}; + if (streamEncryption) + delete streamEncryption; + if (aesEncryption) + delete aesEncryption; - a = anBuf[0]; - b = anBuf[1]; - c = anBuf[2]; - d = anBuf[3]; + aesEncryption = new CryptoPP::AES::Encryption(m_anEncryptionKey, 32); + streamEncryption = new CryptoPP::CBC_Mode_ExternalCipher::Encryption( *aesEncryption, empty); + } - MD5STEP(OptFunc1, a, b, c, d, anIn[0] + 0xd76aa478, 7); - MD5STEP(OptFunc1, d, a, b, c, anIn[1] + 0xe8c7b756, 12); - MD5STEP(OptFunc1, c, d, a, b, anIn[2] + 0x242070db, 17); - MD5STEP(OptFunc1, b, c, d, a, anIn[3] + 0xc1bdceee, 22); - MD5STEP(OptFunc1, a, b, c, d, anIn[4] + 0xf57c0faf, 7); - MD5STEP(OptFunc1, d, a, b, c, anIn[5] + 0x4787c62a, 12); - MD5STEP(OptFunc1, c, d, a, b, anIn[6] + 0xa8304613, 17); - MD5STEP(OptFunc1, b, c, d, a, anIn[7] + 0xfd469501, 22); - MD5STEP(OptFunc1, a, b, c, d, anIn[8] + 0x698098d8, 7); - MD5STEP(OptFunc1, d, a, b, c, anIn[9] + 0x8b44f7af, 12); - MD5STEP(OptFunc1, c, d, a, b, anIn[10] + 0xffff5bb1, 17); - MD5STEP(OptFunc1, b, c, d, a, anIn[11] + 0x895cd7be, 22); - MD5STEP(OptFunc1, a, b, c, d, anIn[12] + 0x6b901122, 7); - MD5STEP(OptFunc1, d, a, b, c, anIn[13] + 0xfd987193, 12); - MD5STEP(OptFunc1, c, d, a, b, anIn[14] + 0xa679438e, 17); - MD5STEP(OptFunc1, b, c, d, a, anIn[15] + 0x49b40821, 22); + std::string m_sOwnerPassword; + std::string m_sUserPassword; + BYTE m_anEncryptionKey[32]; - MD5STEP(OptFunc2, a, b, c, d, anIn[1] + 0xf61e2562, 5); - MD5STEP(OptFunc2, d, a, b, c, anIn[6] + 0xc040b340, 9); - MD5STEP(OptFunc2, c, d, a, b, anIn[11] + 0x265e5a51, 14); - MD5STEP(OptFunc2, b, c, d, a, anIn[0] + 0xe9b6c7aa, 20); - MD5STEP(OptFunc2, a, b, c, d, anIn[5] + 0xd62f105d, 5); - MD5STEP(OptFunc2, d, a, b, c, anIn[10] + 0x02441453, 9); - MD5STEP(OptFunc2, c, d, a, b, anIn[15] + 0xd8a1e681, 14); - MD5STEP(OptFunc2, b, c, d, a, anIn[4] + 0xe7d3fbc8, 20); - MD5STEP(OptFunc2, a, b, c, d, anIn[9] + 0x21e1cde6, 5); - MD5STEP(OptFunc2, d, a, b, c, anIn[14] + 0xc33707d6, 9); - MD5STEP(OptFunc2, c, d, a, b, anIn[3] + 0xf4d50d87, 14); - MD5STEP(OptFunc2, b, c, d, a, anIn[8] + 0x455a14ed, 20); - MD5STEP(OptFunc2, a, b, c, d, anIn[13] + 0xa9e3e905, 5); - MD5STEP(OptFunc2, d, a, b, c, anIn[2] + 0xfcefa3f8, 9); - MD5STEP(OptFunc2, c, d, a, b, anIn[7] + 0x676f02d9, 14); - MD5STEP(OptFunc2, b, c, d, a, anIn[12] + 0x8d2a4c8a, 20); - - MD5STEP(OptFunc3, a, b, c, d, anIn[5] + 0xfffa3942, 4); - MD5STEP(OptFunc3, d, a, b, c, anIn[8] + 0x8771f681, 11); - MD5STEP(OptFunc3, c, d, a, b, anIn[11] + 0x6d9d6122, 16); - MD5STEP(OptFunc3, b, c, d, a, anIn[14] + 0xfde5380c, 23); - MD5STEP(OptFunc3, a, b, c, d, anIn[1] + 0xa4beea44, 4); - MD5STEP(OptFunc3, d, a, b, c, anIn[4] + 0x4bdecfa9, 11); - MD5STEP(OptFunc3, c, d, a, b, anIn[7] + 0xf6bb4b60, 16); - MD5STEP(OptFunc3, b, c, d, a, anIn[10] + 0xbebfbc70, 23); - MD5STEP(OptFunc3, a, b, c, d, anIn[13] + 0x289b7ec6, 4); - MD5STEP(OptFunc3, d, a, b, c, anIn[0] + 0xeaa127fa, 11); - MD5STEP(OptFunc3, c, d, a, b, anIn[3] + 0xd4ef3085, 16); - MD5STEP(OptFunc3, b, c, d, a, anIn[6] + 0x04881d05, 23); - MD5STEP(OptFunc3, a, b, c, d, anIn[9] + 0xd9d4d039, 4); - MD5STEP(OptFunc3, d, a, b, c, anIn[12] + 0xe6db99e5, 11); - MD5STEP(OptFunc3, c, d, a, b, anIn[15] + 0x1fa27cf8, 16); - MD5STEP(OptFunc3, b, c, d, a, anIn[2] + 0xc4ac5665, 23); - - MD5STEP(OptFunc4, a, b, c, d, anIn[0] + 0xf4292244, 6); - MD5STEP(OptFunc4, d, a, b, c, anIn[7] + 0x432aff97, 10); - MD5STEP(OptFunc4, c, d, a, b, anIn[14] + 0xab9423a7, 15); - MD5STEP(OptFunc4, b, c, d, a, anIn[5] + 0xfc93a039, 21); - MD5STEP(OptFunc4, a, b, c, d, anIn[12] + 0x655b59c3, 6); - MD5STEP(OptFunc4, d, a, b, c, anIn[3] + 0x8f0ccc92, 10); - MD5STEP(OptFunc4, c, d, a, b, anIn[10] + 0xffeff47d, 15); - MD5STEP(OptFunc4, b, c, d, a, anIn[1] + 0x85845dd1, 21); - MD5STEP(OptFunc4, a, b, c, d, anIn[8] + 0x6fa87e4f, 6); - MD5STEP(OptFunc4, d, a, b, c, anIn[15] + 0xfe2ce6e0, 10); - MD5STEP(OptFunc4, c, d, a, b, anIn[6] + 0xa3014314, 15); - MD5STEP(OptFunc4, b, c, d, a, anIn[13] + 0x4e0811a1, 21); - MD5STEP(OptFunc4, a, b, c, d, anIn[4] + 0xf7537e82, 6); - MD5STEP(OptFunc4, d, a, b, c, anIn[11] + 0xbd3af235, 10); - MD5STEP(OptFunc4, c, d, a, b, anIn[2] + 0x2ad7d2bb, 15); - MD5STEP(OptFunc4, b, c, d, a, anIn[9] + 0xeb86d391, 21); - - anBuf[0] += a; - anBuf[1] += b; - anBuf[2] += c; - anBuf[3] += d; - } - //---------------------------------------------------------------------------------------- - // CMd5 - //---------------------------------------------------------------------------------------- - CMd5::CMd5() - { - Init(); - }; - void CMd5::Init() - { - m_anBuf[0] = 0x67452301; - m_anBuf[1] = 0xefcdab89; - m_anBuf[2] = 0x98badcfe; - m_anBuf[3] = 0x10325476; - - m_anBits[0] = 0; - m_anBits[1] = 0; - - MemSet(m_anIn, 0x00, 64 * sizeof(BYTE)); - } - void CMd5::Update(const BYTE* pBuffer, unsigned int unLen) - { - // Update bitcount - unsigned int nTempBit = m_anBits[0]; - - if ((m_anBits[0] = nTempBit + (unLen << 3)) < nTempBit) - m_anBits[1]++; // Carry from low to high - - m_anBits[1] += unLen >> 29; - nTempBit = (nTempBit >> 3) & 0x3f; // Bytes already in shsInfo->data - - // Handle any leading odd-sized chunks - if (nTempBit) - { - BYTE *pTemp = (BYTE *)m_anIn + nTempBit; - - nTempBit = 64 - nTempBit; - if (unLen < nTempBit && pBuffer) - { - MemCpy(pTemp, pBuffer, unLen); - return; - } - - if (pBuffer) - MemCpy(pTemp, pBuffer, nTempBit); - - MD5ByteReverse(m_anIn, 16); - MD5Transform(m_anBuf, (unsigned int *)m_anIn); - pBuffer += nTempBit; - unLen -= nTempBit; - } - - // Process data in 64-byte chunks - while (unLen >= 64) - { - MemCpy(m_anIn, pBuffer, 64); - MD5ByteReverse(m_anIn, 16); - MD5Transform(m_anBuf, (unsigned int *)m_anIn); - pBuffer += 64; - unLen -= 64; - } - - // Handle any remaining bytes of data. - MemCpy(m_anIn, pBuffer, unLen); - } - // Final wrapup - pad to 64-byte boundary with the bit pattern - // 1 0* (64-bit count of bits processed, MSB-first) - void CMd5::Final(BYTE anDigest[16]) - { - // Вычисляем количество байтов по модулю 64 - unsigned int nCount = (m_anBits[0] >> 3) & 0x3F; - - // Устанавливаем первый символ в дополнительной строке(padding) значением 0x80. - // Это безопасно, поскольку всегда как минимум один байт свободен. - BYTE *pTemp = m_anIn + nCount; - *pTemp++ = 0x80; - - // Bytes of padding needed to make 64 bytes - nCount = 64 - 1 - nCount; - - // Pad out to 56 mod 64 - if (nCount < 8) - { - // Two lots of padding: Pad the first block to 64 bytes - MemSet(pTemp, 0, nCount); - MD5ByteReverse(m_anIn, 16); - MD5Transform(m_anBuf, (unsigned int *)m_anIn); - - // Now fill the next block with 56 bytes - MemSet(m_anIn, 0, 56); - } - else - { - // Pad block to 56 bytes - MemSet(pTemp, 0, nCount - 8); - } - MD5ByteReverse(m_anIn, 14); - - // Append length in bits and transform - ((unsigned int *)m_anIn)[14] = m_anBits[0]; - ((unsigned int *)m_anIn)[15] = m_anBits[1]; - - MD5Transform(m_anBuf, (unsigned int *)m_anIn); - MD5ByteReverse((BYTE *)m_anBuf, 4); - MemCpy((BYTE *)anDigest, (BYTE *)m_anBuf, 16); - Clear(); // In case it's sensitive - } - void CMd5::Clear() - { - MemSet(m_anBits, 0, 2 * sizeof(unsigned int)); - MemSet(m_anBuf, 0, 4 * sizeof(unsigned int)); - MemSet(m_anIn, 0x00, 64 * sizeof(BYTE)); - } - //---------------------------------------------------------------------------------------- - // CArc4 - //---------------------------------------------------------------------------------------- - void CArc4::Init(const BYTE* pKey, unsigned int unKeyLen) - { - BYTE pTempArray[ARC4_BUF_SIZE]; - unsigned int nJ = 0; - - for (unsigned int nIndex = 0; nIndex < ARC4_BUF_SIZE; nIndex++) - m_anState[nIndex] = nIndex; - - for (unsigned int nIndex = 0; nIndex < ARC4_BUF_SIZE; nIndex++) - pTempArray[nIndex] = pKey[nIndex % unKeyLen]; - - for (unsigned int nIndex = 0; nIndex < ARC4_BUF_SIZE; nIndex++) - { - nJ = (nJ + m_anState[nIndex] + pTempArray[nIndex]) % ARC4_BUF_SIZE; - - BYTE nTemp = m_anState[nIndex]; - m_anState[nIndex] = m_anState[nJ]; - m_anState[nJ] = nTemp; - } - - m_nIndex1 = 0; - m_nIndex2 = 0; - } - void CArc4::CryptBuf(const BYTE* pIn, BYTE* pOut, unsigned int unLen) - { - for (unsigned int nIndex = 0; nIndex < unLen; nIndex++) - { - m_nIndex1 = (m_nIndex1 + 1) % 256; - m_nIndex2 = (m_nIndex2 + m_anState[m_nIndex1]) % 256; - - BYTE nTemp = m_anState[m_nIndex1]; - m_anState[m_nIndex1] = m_anState[m_nIndex2]; - m_anState[m_nIndex2] = nTemp; - - unsigned int nTempIndex = (m_anState[m_nIndex1] + m_anState[m_nIndex2]) % 256; - BYTE nKoef = m_anState[nTempIndex]; - - pOut[nIndex] = pIn[nIndex] ^ nKoef; - } - } - //---------------------------------------------------------------------------------------- - // CEncrypt - //---------------------------------------------------------------------------------------- - CEncrypt::CEncrypt() - { - Init(); - } - void CEncrypt::Init() - { - m_eMode = encryptmode_R2; - m_unKeyLen = 5; - MemCpy(m_anOwnerPassword, c_sPaddingString, PASSWD_LEN); - MemCpy(m_anUserPassword, c_sPaddingString, PASSWD_LEN); + CryptoPP::AES::Encryption *aesEncryption; + CryptoPP::StreamTransformation *streamEncryption; + }; + CEncrypt::CEncrypt() : m_unKeyLen(32) + { + impl = new Impl(); + m_unPermission = ENABLE_PRINT | ENABLE_EDIT_ALL | ENABLE_COPY | ENABLE_EDIT | PERMISSION_PAD; - - MemSet(m_anOwnerKey, 0, PASSWD_LEN); - MemSet(m_anUserKey, 0, PASSWD_LEN); + MemSet(m_anEncryptID, 0, ID_LEN); - MemSet(m_anEncryptionKey, 0, MD5_KEY_LEN + 5); - MemSet(m_anMD5EncryptionKey, 0, MD5_KEY_LEN); } - void CEncrypt::CreateUserKey() + CEncrypt::~CEncrypt() + { + delete impl; + } + void CEncrypt::SetPasswords(const std::string &sUserPassword, const std::string &sOwnerPassword) + { + impl->m_sUserPassword = sUserPassword; + impl->m_sOwnerPassword = sOwnerPassword; + } + bool CEncrypt::MakeFileKey3(const std::string &sPassword, unsigned char *pHash, int nHashSize, unsigned char *pHash2, int nHashSize2) + { + if (!pHash) return false; + + int size = 64 * (sPassword.length() + 64 + nHashSize2); // max + + unsigned char K[64]; //max size sha + unsigned char *K1 = new unsigned char[size]; + unsigned char *E = new unsigned char[size]; + + int hash_size = nHashSize; + memcpy(K, pHash, nHashSize); + + int iteration = 0; + + while( (iteration < 64) || (iteration < E[size - 1] + 32)) + { + size = 0; + for (int i = 0; i < 64; i++) + { + memcpy(K1 + size, sPassword.c_str(), sPassword.length()); size += sPassword.length(); + memcpy(K1 + size, K, hash_size); size += hash_size; + if (pHash2) + { + memcpy(K1 + size, pHash2, nHashSize2); size += nHashSize2; + } + } + + CryptoPP::AES::Encryption aesEncryption(K, 16); + CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, K + 16); + + CryptoPP::StreamTransformationFilter stfEncryption(cbcEncryption, new CryptoPP::ArraySink( E, size), CryptoPP::StreamTransformationFilter::NO_PADDING); + + stfEncryption.Put( K1, size); + stfEncryption.MessageEnd(); +//---------------------------------------------------------- + int E_mod_3 = 0; + for (unsigned int i = 0; i < 16; ++i) + { + E_mod_3 += E[i]; + } + E_mod_3 %= 3; + + hash_size = SHA(E_mod_3, E, size, K); + + iteration++; + } + + delete []K1; + delete []E; + + memcpy (pHash, K, 32); // pHash - from sha256 + return true; + } + + void CEncrypt::CreateUserKey() { - CArc4 oContext; + CryptoPP::RandomPool prng; - // Algorithm 3.4/5 step1 - // Algorithm 3.4 step2 - oContext.Init(m_anEncryptionKey, m_unKeyLen); - oContext.CryptBuf(c_sPaddingString, m_anUserKey, PASSWD_LEN); + CryptoPP::SecByteBlock salt(16); + CryptoPP::OS_GenerateRandomBlock(false, salt, salt.size()); + prng.IncorporateEntropy(salt, salt.size()); - if (encryptmode_R3 == m_eMode) - { - CMd5 oMmd5; - BYTE anDigest[MD5_KEY_LEN]; - BYTE anDigest2[MD5_KEY_LEN]; + memcpy(m_anUserKey + 32, salt.data(), salt.size()); - // Algorithm 3.5 step2 (same as Algorithm3.2 step2) - oMmd5.Init(); - oMmd5.Update(c_sPaddingString, PASSWD_LEN); + CryptoPP::SHA256 hash; - // Algorithm 3.5 step3 - oMmd5.Update(m_anEncryptID, ID_LEN); - oMmd5.Final(anDigest); + hash.Update( (unsigned char*) impl->m_sUserPassword.c_str(), impl->m_sUserPassword.length()); + hash.Update( m_anUserKey + 32, 8); - // Algorithm 3.5 step4 - oContext.Init(m_anEncryptionKey, m_unKeyLen); - oContext.CryptBuf(anDigest, anDigest2, MD5_KEY_LEN); + CryptoPP::SecByteBlock pHashData(hash.DigestSize()); + hash.Final(pHashData); - // Algorithm 3.5 step5 - for (unsigned int nI = 1; nI <= 19; nI++) - { - BYTE pNewKey[MD5_KEY_LEN]; - for (unsigned int nJ = 0; nJ < m_unKeyLen; nJ++) - pNewKey[nJ] = m_anEncryptionKey[nJ] ^ nI; + if (MakeFileKey3(impl->m_sUserPassword, pHashData.data(), pHashData.size())) + { + memcpy(m_anUserKey, pHashData.data(), pHashData.size()); - MemCpy(anDigest, anDigest2, MD5_KEY_LEN); + hash.Update( (unsigned char*) impl->m_sUserPassword.c_str(), impl->m_sUserPassword.length()); + hash.Update( m_anUserKey + 40, 8); - oContext.Init(pNewKey, m_unKeyLen); - oContext.CryptBuf(anDigest, anDigest2, MD5_KEY_LEN); - } + CryptoPP::SecByteBlock pHashKeyData(hash.DigestSize()); + hash.Final(pHashKeyData); - // use the result of Algorithm 3.4 as 'arbitrary padding' - MemSet(m_anUserKey, 0, PASSWD_LEN); - MemCpy(m_anUserKey, anDigest2, MD5_KEY_LEN); - } + MakeFileKey3(impl->m_sUserPassword, pHashKeyData.data(), pHashKeyData.size()); + unsigned char empty[16] = {}; + + CryptoPP::AES::Encryption aesEncryption(pHashKeyData.data(), pHashKeyData.size()); + CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, empty); + + CryptoPP::StreamTransformationFilter stfEncryption(cbcEncryption, new CryptoPP::ArraySink( m_anUserEncryptKey, 32), CryptoPP::StreamTransformationFilter::NO_PADDING ); + stfEncryption.Put2(impl->m_anEncryptionKey, 32, 1, true); + stfEncryption.MessageEnd(); + } } void CEncrypt::CreateOwnerKey() { - CArc4 oArc4; - CMd5 oMd5; + CryptoPP::RandomPool prng; - BYTE anDigest[MD5_KEY_LEN]; - BYTE anTempPassword[PASSWD_LEN]; + CryptoPP::SecByteBlock salt(16); + CryptoPP::OS_GenerateRandomBlock(false, salt, salt.size()); + prng.IncorporateEntropy(salt, salt.size()); - // create md5-digest using the value of anOwnerPassword - // Algorithm 3.3 step 2 - oMd5.Init(); - oMd5.Update(m_anOwnerPassword, PASSWD_LEN); - oMd5.Final(anDigest); + memcpy(m_anOwnerKey + 32, salt.data(), salt.size()); - // Algorithm 3.3 step 3 (Revision 3 only) - if (encryptmode_R3 == m_eMode) - { - for (unsigned int nIndex = 0; nIndex < 50; nIndex++) - { - oMd5.Init(); - oMd5.Update(anDigest, m_unKeyLen); - oMd5.Final(anDigest); - } - } + CryptoPP::SHA256 hash; - // Algorithm 3.3 step 4 - oArc4.Init(anDigest, m_unKeyLen); + hash.Update( (unsigned char*) impl->m_sOwnerPassword.c_str(), impl->m_sOwnerPassword.length()); + hash.Update( m_anOwnerKey + 32, 8); + hash.Update( m_anUserKey, 48); - // Algorithm 3.3 step 6 - oArc4.CryptBuf(m_anUserPassword, anTempPassword, PASSWD_LEN); + CryptoPP::SecByteBlock pHashData(hash.DigestSize()); + hash.Final(pHashData); - // Algorithm 3.3 step 7 - if (encryptmode_R3 == m_eMode) - { - BYTE anTempPassword2[PASSWD_LEN]; + if (MakeFileKey3(impl->m_sOwnerPassword, pHashData.data(), pHashData.size(), m_anUserKey, 48)) + { + memcpy(m_anOwnerKey, pHashData.data(), pHashData.size()); - for (unsigned int i = 1; i <= 19; i++) - { - BYTE anNewKey[MD5_KEY_LEN]; + hash.Update( (unsigned char*) impl->m_sOwnerPassword.c_str(), impl->m_sOwnerPassword.length()); + hash.Update( m_anOwnerKey + 40, 8); + hash.Update( m_anUserKey, 48); - for (unsigned int j = 0; j < m_unKeyLen; j++) - anNewKey[j] = anDigest[j] ^ i; + CryptoPP::SecByteBlock pHashKeyData(hash.DigestSize()); + hash.Final(pHashKeyData); - MemCpy(anTempPassword2, anTempPassword, PASSWD_LEN); - oArc4.Init(anNewKey, m_unKeyLen); - oArc4.CryptBuf(anTempPassword2, anTempPassword, PASSWD_LEN); - } - } + MakeFileKey3(impl->m_sOwnerPassword, pHashKeyData.data(), pHashKeyData.size(), m_anUserKey, 48); + unsigned char empty[16] = {}; - // Algorithm 3.3 step 8 - MemCpy(m_anOwnerKey, anTempPassword, PASSWD_LEN); + CryptoPP::AES::Encryption aesEncryption(pHashKeyData.data(), pHashKeyData.size()); + CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, empty); + + CryptoPP::StreamTransformationFilter stfEncryption(cbcEncryption, new CryptoPP::ArraySink( m_anOwnerEncryptKey, 32), CryptoPP::StreamTransformationFilter::NO_PADDING ); + stfEncryption.Put2(impl->m_anEncryptionKey, 32, 1, true); + stfEncryption.MessageEnd(); + } } void CEncrypt::CreateEncryptionKey() { - CMd5 oMd5; - BYTE anTempFlag[4]; + CryptoPP::RandomPool prng; - // Algorithm3.2 step2 - oMd5.Init(); - oMd5.Update(m_anUserPassword, PASSWD_LEN); + CryptoPP::SecByteBlock key(32); + CryptoPP::OS_GenerateRandomBlock(false, key, key.size()); + prng.IncorporateEntropy(key, key.size()); - // Algorithm3.2 step3 - oMd5.Update(m_anOwnerKey, PASSWD_LEN); + memcpy(impl->m_anEncryptionKey, key.data(), key.size()); +//------------------------------------------------------------------- + unsigned long long extended_perms = 0xffffffff00000000LL | m_unPermission; + for (int i = 0; i < 8; ++i) + { + m_anPermEncrypt[i] = static_cast(extended_perms & 0xff); + extended_perms >>= 8; + } + m_anPermEncrypt[8] = /*m_bEncryptMetadata ? 'T' : */'F'; + m_anPermEncrypt[9] = 'a'; + m_anPermEncrypt[10] = 'd'; + m_anPermEncrypt[11] = 'b'; + + CryptoPP::SecByteBlock p(4); + CryptoPP::OS_GenerateRandomBlock(false, p, p.size()); + prng.IncorporateEntropy(p, p.size()); - // Algorithm3.2 step4 - anTempFlag[0] = m_unPermission; - anTempFlag[1] = (m_unPermission >> 8); - anTempFlag[2] = (m_unPermission >> 16); - anTempFlag[3] = (m_unPermission >> 24); + memcpy(m_anPermEncrypt + 12, p.data(), p.size()); - oMd5.Update(anTempFlag, 4); + unsigned char empty[16] = {}; + + CryptoPP::AES::Encryption aesEncryption(impl->m_anEncryptionKey, 32); + + CryptoPP::CipherModeFinalTemplate_ExternalCipher ecbEncryption(aesEncryption, empty ); - // Algorithm3.2 step5 - oMd5.Update(m_anEncryptID, ID_LEN); - oMd5.Final(m_anEncryptionKey); - - // Algorithm 3.2 step6 (Revision 3 only) - if (encryptmode_R3 == m_eMode) - { - for (unsigned int nIndex = 0; nIndex < 50; nIndex++) - { - oMd5.Init(); - oMd5.Update(m_anEncryptionKey, m_unKeyLen); - oMd5.Final(m_anEncryptionKey); - } - } + CryptoPP::StreamTransformationFilter stfEncryption(ecbEncryption, new CryptoPP::ArraySink( m_anPermEncrypt, 16), CryptoPP::StreamTransformationFilter::NO_PADDING ); + stfEncryption.Put2(m_anPermEncrypt, 16, 1, true); + stfEncryption.MessageEnd(); } void CEncrypt::InitKey(unsigned int unObjectId, unsigned short unGenNo) { - m_anEncryptionKey[m_unKeyLen + 0] = (BYTE) unObjectId; - m_anEncryptionKey[m_unKeyLen + 1] = (BYTE)(unObjectId >> 8); - m_anEncryptionKey[m_unKeyLen + 2] = (BYTE)(unObjectId >> 16); - m_anEncryptionKey[m_unKeyLen + 3] = (BYTE) unGenNo; - m_anEncryptionKey[m_unKeyLen + 4] = (BYTE)(unGenNo >> 8); - - CMd5 oMd5; - oMd5.Init(); - oMd5.Update(m_anEncryptionKey, m_unKeyLen + 5); - oMd5.Final(m_anMD5EncryptionKey); - - unsigned int unKeyLen = (m_unKeyLen + 5 > ENCRYPT_KEY_MAX) ? ENCRYPT_KEY_MAX : m_unKeyLen + 5; - m_oArc4Context.Init(m_anMD5EncryptionKey, unKeyLen); } void CEncrypt::Reset() - { - unsigned int unKeyLen = (m_unKeyLen + 5 > ENCRYPT_KEY_MAX) ? ENCRYPT_KEY_MAX : m_unKeyLen + 5; - m_oArc4Context.Init(m_anMD5EncryptionKey, unKeyLen); + { + impl->Reset(); } - void CEncrypt::CryptBuf(const BYTE* pSrc, BYTE* pDst, unsigned int unLen) + void CEncrypt::CryptBuf(const BYTE* pSrc, BYTE* pDst, unsigned int unLen, bool bLast) { - m_oArc4Context.CryptBuf(pSrc, pDst, unLen); - } + CryptoPP::StreamTransformationFilter stfEncryption(*impl->streamEncryption, new CryptoPP::ArraySink( pDst, unLen), CryptoPP::StreamTransformationFilter::ZEROS_PADDING ); + + stfEncryption.Put2(pSrc, unLen, bLast ? 1 : 0, true); + stfEncryption.MessageEnd(); + } void CEncrypt::SetPermission(unsigned int unPermission) { m_unPermission = unPermission; } - void CEncrypt::SetMode(EEncryptMode eMode, unsigned int unKeyLen) - { - if (encryptmode_R2 == eMode) - m_unKeyLen = 5; - else - { - if (unKeyLen >= 5 && unKeyLen <= 16) - m_unKeyLen = unKeyLen; - else - m_unKeyLen = 16; - } - m_eMode = eMode; - } -} \ No newline at end of file +} diff --git a/PdfWriter/Src/Encrypt.h b/PdfWriter/Src/Encrypt.h index ed9f52f879..da7c9ee363 100644 --- a/PdfWriter/Src/Encrypt.h +++ b/PdfWriter/Src/Encrypt.h @@ -35,85 +35,41 @@ #include "Utils.h" #define ID_LEN 16 -#define PASSWD_LEN 32 -#define ENCRYPT_KEY_MAX 16 -#define MD5_KEY_LEN 16 #define PERMISSION_PAD 0xFFFFFFC0 -#define ARC4_BUF_SIZE 256 namespace PdfWriter { - void PadOrTrancatePassword(const char *sPassword, BYTE *pNewPassword); - - //---------------------------------------------------------------------------------------- - // - // The code implements MD5 message-digest algorithm. - // To compute the message digest of a chunk of bytes, declare an - // MD5Context structure, pass it to MD5Init, call MD5Update as - // needed on buffers full of bytes, and then call MD5Final, which - // will fill a supplied 16-byte array with the digest. - // - //---------------------------------------------------------------------------------------- - class CMd5 - { - public: - - CMd5(); - void Init(); - void Update(const BYTE* pBuffer, unsigned int unLen); - void Final(BYTE anDigest[16]); - - private: - - void Clear(); - - private: - - unsigned int m_anBuf[4]; - unsigned int m_anBits[2]; - BYTE m_anIn[64]; - }; - class CArc4 - { - public: - - void Init(const BYTE* pKey, unsigned int unKeyLen); - void CryptBuf(const BYTE* pIn, BYTE* pOut, unsigned int unLen); - - private: - BYTE m_nIndex1; - BYTE m_nIndex2; - BYTE m_anState[ARC4_BUF_SIZE]; - }; class CEncrypt { public: - CEncrypt(); + CEncrypt(); + virtual ~CEncrypt(); - void Init(); void CreateUserKey(); void CreateOwnerKey(); void CreateEncryptionKey(); void InitKey(unsigned int unObjectId, unsigned short unGenNo); void Reset(); - void CryptBuf(const BYTE* pSrc, BYTE* pDst, unsigned int unLen); + void CryptBuf(const BYTE* pSrc, BYTE* pDst, unsigned int unLen, bool bLast); void SetPermission(unsigned int unPermission); - void SetMode(EEncryptMode eMode, unsigned int unKeyLen); - + void SetPasswords(const std::string &sUserPassword, const std::string &sOwnerPassword); private: + class Impl; + Impl *impl; - EEncryptMode m_eMode; - unsigned int m_unKeyLen; // unKeyLen должно быть кратно 8, и лежать в отрезке от 40 и до 128 - BYTE m_anOwnerPassword[PASSWD_LEN]; // Owner-Password (не шифрованный) - BYTE m_anUserPassword[PASSWD_LEN]; // User-Password (не шифрованный) - BYTE m_anOwnerKey[PASSWD_LEN]; // Owner-Password (шифрованный) - BYTE m_anUserKey[PASSWD_LEN]; // User-Password (шифрованный) - unsigned int m_unPermission; - BYTE m_anEncryptID[ID_LEN]; - BYTE m_anEncryptionKey[MD5_KEY_LEN + 5]; - BYTE m_anMD5EncryptionKey[MD5_KEY_LEN]; - CArc4 m_oArc4Context; + bool MakeFileKey3(const std::string &sPassword, unsigned char *pHash, int nHashSize, unsigned char *pHash2 = NULL, int nHashSize2 = 0); + + unsigned int m_unKeyLen; + + BYTE m_anOwnerKey[48]; //O + BYTE m_anUserKey[48]; //U + BYTE m_anOwnerEncryptKey[32]; //OE + BYTE m_anUserEncryptKey[32]; //UE + unsigned int m_unPermission; //P + BYTE m_anPermEncrypt[16]; //Perm + + BYTE m_anEncryptID[ID_LEN]; friend class CEncryptDict; friend class CDocument; diff --git a/PdfWriter/Src/EncryptDictionary.cpp b/PdfWriter/Src/EncryptDictionary.cpp index 6116e2e389..cc88127544 100644 --- a/PdfWriter/Src/EncryptDictionary.cpp +++ b/PdfWriter/Src/EncryptDictionary.cpp @@ -35,16 +35,17 @@ #include +#include "../../Common/3dParty/cryptopp/md5.h" +#include "../../UnicodeConverter/UnicodeConverter.h" + namespace PdfWriter { - //---------------------------------------------------------------------------------------- + //---------------------------------------------------------------------------------------- // CEncryptDict //---------------------------------------------------------------------------------------- CEncryptDict::CEncryptDict(CXref* pXref) { m_pEncrypt = new CEncrypt(); - if (m_pEncrypt) - m_pEncrypt->Init(); pXref->Add(this); } @@ -55,11 +56,10 @@ namespace PdfWriter } void CEncryptDict::CreateId(CInfoDict* pInfo, CXref* pXref) { - CMd5 oMd5; - oMd5.Init(); + CryptoPP::MD5 hash; std::time_t oTime = time(0); - oMd5.Update((BYTE*)&oTime, sizeof(oTime)); + hash.Update( (BYTE*)&oTime, sizeof(oTime)); // Создаем идентификатор файла по элементам библиотеки Info. if (pInfo) @@ -70,82 +70,107 @@ namespace PdfWriter // Author sTemp = pInfo->GetInfo(InfoAuthor); if ((nLen = StrLen(sTemp, -1)) > 0) - oMd5.Update((const BYTE *)sTemp, nLen); + hash.Update( (const BYTE *)sTemp, nLen ); // Creator sTemp = pInfo->GetInfo(InfoCreator); if ((nLen = StrLen(sTemp, -1)) > 0) - oMd5.Update((const BYTE *)sTemp, nLen); + hash.Update( (const BYTE *)sTemp, nLen); // Producer sTemp = pInfo->GetInfo(InfoProducer); if ((nLen = StrLen(sTemp, -1)) > 0) - oMd5.Update((const BYTE *)sTemp, nLen); + hash.Update( (const BYTE *)sTemp, nLen); // Title sTemp = pInfo->GetInfo(InfoTitle); if ((nLen = StrLen(sTemp, -1)) > 0) - oMd5.Update((const BYTE *)sTemp, nLen); + hash.Update( (const BYTE *)sTemp, nLen); // Subject sTemp = pInfo->GetInfo(InfoSubject); if ((nLen = StrLen(sTemp, -1)) > 0) - oMd5.Update((const BYTE *)sTemp, nLen); + hash.Update( (const BYTE *)sTemp, nLen); // Keywords sTemp = pInfo->GetInfo(InfoKeyWords); if ((nLen = StrLen(sTemp, -1)) > 0) - oMd5.Update((const BYTE *)sTemp, nLen); + hash.Update( (const BYTE *)sTemp, nLen); int nXrefEntriesCount = pXref->GetCount(); - oMd5.Update((const BYTE *)&nXrefEntriesCount, sizeof(unsigned int)); + hash.Update( (const BYTE *)&nXrefEntriesCount, sizeof(unsigned int)); } - oMd5.Final(m_pEncrypt->m_anEncryptID); + CryptoPP::SecByteBlock buffer(hash.DigestSize()); + hash.Final(buffer); + + memcpy(m_pEncrypt->m_anEncryptID, buffer.BytePtr(), buffer.size()); + } + std::string CEncryptDict::PadOrTrancatePassword(const std::wstring & wsPassword) + { + NSUnicodeConverter::CUnicodeConverter conv; + std::string sNewPassword = conv.SASLprepToUtf8(wsPassword); + + if (sNewPassword.length() > 127) + sNewPassword = sNewPassword.substr(0, 127); + + return sNewPassword; } - void CEncryptDict::SetPassword(const char* sOwnerPassword, const char* sUserPassword) + void CEncryptDict::SetPasswords(const std::wstring & wsOwnerPassword, const std::wstring & wsUserPassword) { - if (0 == StrLen(sOwnerPassword, 2)) - return; + std::string sOwnerPassword = PadOrTrancatePassword(wsOwnerPassword); + std::string sUserPassword = PadOrTrancatePassword(wsUserPassword); - if (sOwnerPassword && sUserPassword && 0 == StrCmp(sOwnerPassword, sUserPassword)) - return; - - PadOrTrancatePassword(sOwnerPassword, m_pEncrypt->m_anOwnerPassword); - PadOrTrancatePassword(sUserPassword, m_pEncrypt->m_anUserPassword); + m_pEncrypt->SetPasswords(sUserPassword, sOwnerPassword); } void CEncryptDict::Prepare(CInfoDict* pInfo, CXref* pXref) { CreateId(pInfo, pXref); - m_pEncrypt->CreateOwnerKey(); - m_pEncrypt->CreateEncryptionKey(); - m_pEncrypt->CreateUserKey(); + m_pEncrypt->CreateEncryptionKey(); + m_pEncrypt->CreateUserKey(); + m_pEncrypt->CreateOwnerKey(); - CBinaryObject* pOwnerKey = new CBinaryObject(m_pEncrypt->m_anOwnerKey, PASSWD_LEN); - if (!pOwnerKey) - return; + Add("Filter", "Standard"); + Add("V", 5); + Add("Length", m_pEncrypt->m_unKeyLen * 8); + Add("R", 6); + Add("P", m_pEncrypt->m_unPermission); - Add("O", pOwnerKey); + CDictObject* pCF = new CDictObject(); + + CDictObject* pStdCF = new CDictObject(); + pCF->Add("StdCF", pStdCF); - CBinaryObject* pUserKey = new CBinaryObject(m_pEncrypt->m_anUserKey, PASSWD_LEN); - if (!pUserKey) - return; + pStdCF->Add("CFM", "AESV3"); + pStdCF->Add("AuthEvent", "DocOpen"); + pStdCF->Add("Length", m_pEncrypt->m_unKeyLen); - Add("U", pUserKey); + Add("CF", pCF); - Add("Filter", "Standard"); - if (encryptmode_R2 == m_pEncrypt->m_eMode) - { - Add("V", 1); - Add("R", 2); - } - else if (encryptmode_R3 == m_pEncrypt->m_eMode) - { - Add("V", 2); - Add("R", 3); - Add("Length", m_pEncrypt->m_unKeyLen * 8); - } - Add("P", m_pEncrypt->m_unPermission); - } -} \ No newline at end of file + CBinaryObject* pUserKey = new CBinaryObject(m_pEncrypt->m_anUserKey, 48); + if (!pUserKey) + return; + + CBinaryObject* pUserEncryptKey = new CBinaryObject(m_pEncrypt->m_anUserEncryptKey, 32); + if (!pUserKey) + return; + + Add("U", pUserKey); + Add("UE", pUserEncryptKey); + + CBinaryObject* pOwnerKey = new CBinaryObject(m_pEncrypt->m_anOwnerKey, 48); + if (!pOwnerKey) + return; + + CBinaryObject* pOwnerEncryptKey = new CBinaryObject(m_pEncrypt->m_anOwnerEncryptKey, 32); + if (!pOwnerKey) + return; + + Add("O", pOwnerKey); + Add("OE", pOwnerEncryptKey); + + CBinaryObject* pEncryptPerm = new CBinaryObject(m_pEncrypt->m_anPermEncrypt, 16); + Add("Perms", pEncryptPerm); + } +} diff --git a/PdfWriter/Src/EncryptDictionary.h b/PdfWriter/Src/EncryptDictionary.h index e3452f316d..20b20e0ee8 100644 --- a/PdfWriter/Src/EncryptDictionary.h +++ b/PdfWriter/Src/EncryptDictionary.h @@ -50,7 +50,7 @@ namespace PdfWriter } void CreateId(CInfoDict* pInfo, CXref* pXref); - void SetPassword(const char* sOwnerPassword, const char* sUserPassword); + void SetPasswords(const std::wstring & wsOwnerPassword, const std::wstring & wsUserPassword); void Prepare(CInfoDict* pInfo, CXref* pXref); CEncrypt* GetEncrypt() const { @@ -58,6 +58,7 @@ namespace PdfWriter } private: CEncrypt* m_pEncrypt; + std::string PadOrTrancatePassword(const std::wstring & wsPassword); }; } #endif // _PDF_WRITER_SRC_ENCRYPT_DICTIONARY_H diff --git a/PdfWriter/Src/FontCidTT.cpp b/PdfWriter/Src/FontCidTT.cpp index 8a82c26d82..afe5622d94 100644 --- a/PdfWriter/Src/FontCidTT.cpp +++ b/PdfWriter/Src/FontCidTT.cpp @@ -55,13 +55,14 @@ namespace PdfWriter if (!pFace) return nCharIndex; +#ifndef TEST_PDFWRITER_LIB + for (int nIndex = 0; nIndex < pFace->num_charmaps; nIndex++) { FT_CharMap pCharMap = pFace->charmaps[nIndex]; if (FT_Set_Charmap(pFace, pCharMap)) continue; - FT_Encoding pEncoding = pCharMap->encoding; if (FT_ENCODING_UNICODE == pEncoding) @@ -87,11 +88,13 @@ namespace PdfWriter nCharIndex = FT_Get_Char_Index( pFace, unUnicode ); }*/ } +#endif return nCharIndex; } - static int GetSymbolicCmapIndex(FT_Face pFace) + static int GetSymbolicCmapIndex(FT_Face pFace) { +#ifndef TEST_PDFWRITER_LIB TT_OS2 *pOs2 = (TT_OS2 *)FT_Get_Sfnt_Table(pFace, ft_sfnt_os2); if (NULL == pOs2 || 0xFFFF == pOs2->version) return -1; @@ -107,7 +110,7 @@ namespace PdfWriter if (0 == pFace->charmaps[nIndex]->encoding_id && 3 == pFace->charmaps[nIndex]->platform_id) return nIndex; } - +#endif return -1; } //---------------------------------------------------------------------------------------- @@ -151,13 +154,14 @@ namespace PdfWriter if (m_pFontFile) delete m_pFontFile; +#ifndef TEST_PDFWRITER_LIB if (m_pFace) FT_Done_Face(m_pFace); - +#endif if (m_pFaceMemory) delete[] m_pFaceMemory; } - void CFontCidTrueType::CreateCIDFont2(CDictObject* pFont) + void CFontCidTrueType::CreateCIDFont2(CDictObject* pFont) { m_pFont = pFont; pFont->Add("Subtype", "CIDFontType2"); @@ -273,6 +277,7 @@ namespace PdfWriter // Данный символ используется m_mGlyphs.insert(std::pair(unGID, true)); +#ifndef TEST_PDFWRITER_LIB // Если данный символ составной (CompositeGlyf), тогда мы должны учесть все его дочерные символы (subglyfs) if (0 == FT_Load_Glyph(m_pFace, unGID, FT_LOAD_NO_SCALE | FT_LOAD_NO_RECURSE)) { @@ -293,8 +298,8 @@ namespace PdfWriter else m_vWidths.push_back((unsigned int)m_pFace->glyph->metrics.horiAdvance); } +#endif } - pEncodedString[2 * unIndex + 0] = (ushCode >> 8) & 0xFF; pEncodedString[2 * unIndex + 1] = ushCode & 0xFF; } @@ -307,7 +312,7 @@ namespace PdfWriter return m_vWidths.at(ushCode); } - void CFontCidTrueType::BeforeWrite() + void CFontCidTrueType::BeforeWrite() { if (m_pFontFile) { @@ -349,7 +354,7 @@ namespace PdfWriter WriteToUnicode(); } } - bool CFontCidTrueType::GetWidthsAndGids(unsigned short** ppCodeToGid, unsigned int** ppWidths, unsigned char** ppGlyphs, unsigned int& unGlyphsCount) + bool CFontCidTrueType::GetWidthsAndGids(unsigned short** ppCodeToGid, unsigned int** ppWidths, unsigned char** ppGlyphs, unsigned int& unGlyphsCount) { *ppCodeToGid = NULL; *ppWidths = NULL; @@ -397,7 +402,7 @@ namespace PdfWriter unGlyphsCount = m_nGlyphsCount; return true; } - void CFontCidTrueType::WriteToUnicode() + void CFontCidTrueType::WriteToUnicode() { CStream* pS = m_pToUnicodeStream; @@ -433,17 +438,19 @@ namespace PdfWriter pS->WriteStr("endbfchar\n"); m_pToUnicodeStream->WriteStr(c_sToUnicodeFooter); } - void CFontCidTrueType::CloseFontFace() + void CFontCidTrueType::CloseFontFace() { if (m_pFace) { +#ifndef TEST_PDFWRITER_LIB FT_Done_Face(m_pFace); m_pFace = NULL; +#endif } RELEASEARRAYOBJECTS(m_pFaceMemory); } - bool CFontCidTrueType::OpenFontFace() + bool CFontCidTrueType::OpenFontFace() { if (m_pFace) { @@ -464,7 +471,9 @@ namespace PdfWriter if (!m_pFaceMemory) return false; +#ifndef TEST_PDFWRITER_LIB FT_New_Memory_Face(pLibrary, m_pFaceMemory, dwFileSize, m_unFontIndex, &m_pFace); +#endif if (!m_pFace) { RELEASEARRAYOBJECTS(m_pFaceMemory); diff --git a/PdfWriter/Src/Info.cpp b/PdfWriter/Src/Info.cpp index e0f1c4437c..8555bda587 100644 --- a/PdfWriter/Src/Info.cpp +++ b/PdfWriter/Src/Info.cpp @@ -81,7 +81,7 @@ namespace PdfWriter return (const char*)pString->GetString(); } - void CInfoDict::SetInfo(EInfoType eType, const TDate& oDate) + void CInfoDict::SetInfo(EInfoType eType, const TDate& oDate) { char sTemp[DATE_TIME_STR_LEN + 1]; char* pTemp = NULL; @@ -151,7 +151,7 @@ namespace PdfWriter Add(sName, new CStringObject(sTemp)); } - void CInfoDict::SetCreationTime() + void CInfoDict::SetCreationTime() { time_t oTime = time(0); struct tm* oNow = localtime(&oTime); diff --git a/PdfWriter/Src/Objects.cpp b/PdfWriter/Src/Objects.cpp index d3935706f8..7a698a8964 100644 --- a/PdfWriter/Src/Objects.cpp +++ b/PdfWriter/Src/Objects.cpp @@ -194,7 +194,7 @@ namespace PdfWriter //---------------------------------------------------------------------------------------- // CArrayObject //---------------------------------------------------------------------------------------- - void CArrayObject::Add(CObjectBase* pObject) + void CArrayObject::Add(CObjectBase* pObject) { if (!pObject) return; @@ -225,43 +225,43 @@ namespace PdfWriter m_arrList.push_back(pObject); } - void CArrayObject::Add(bool bValue) + void CArrayObject::Add(bool bValue) { CObjectBase* pBool = new CBoolObject(bValue); if (pBool) Add(pBool); } - void CArrayObject::Add(int nValue) + void CArrayObject::Add(int nValue) { CObjectBase* pNumber = new CNumberObject(nValue); if (pNumber) Add(pNumber); } - void CArrayObject::Add(unsigned int unValue) + void CArrayObject::Add(unsigned int unValue) { CObjectBase* pNumber = new CNumberObject((int)unValue); if (pNumber) Add(pNumber); } - void CArrayObject::Add(float fValue) + void CArrayObject::Add(float fValue) { CObjectBase* pReal = new CRealObject(fValue); if (pReal) Add(pReal); } - void CArrayObject::Add(const char* sName) + void CArrayObject::Add(const char* sName) { CObjectBase* pName = new CNameObject(sName); if (pName) Add(pName); } - void CArrayObject::Add(double dValue) + void CArrayObject::Add(double dValue) { CObjectBase* pReal = new CRealObject(dValue); if (pReal) Add(pReal); } - void CArrayObject::Insert(CObjectBase *pTarget, CObjectBase* pObject) + void CArrayObject::Insert(CObjectBase *pTarget, CObjectBase* pObject) { if (!pObject) return; @@ -320,7 +320,7 @@ namespace PdfWriter return pObject; } - void CArrayObject::Clear() + void CArrayObject::Clear() { for (int nIndex = 0, nCount = m_arrList.size(); nIndex < nCount; nIndex++) { @@ -406,7 +406,7 @@ namespace PdfWriter return NULL; } - void CDictObject::Add(const std::string& sKey, CObjectBase* pObject) + void CDictObject::Add(const std::string& sKey, CObjectBase* pObject) { if (!pObject) return; @@ -429,9 +429,9 @@ namespace PdfWriter pObject = pProxy; } pObject->SetDirect(); - m_mList.insert(std::pair(sKey, pObject)); + m_mList.insert(std::make_pair(sKey, pObject)); } - void CDictObject::Remove(const std::string& sKey) + void CDictObject::Remove(const std::string& sKey) { std::map::const_iterator pIter = m_mList.find(sKey); if (m_mList.end() != pIter) @@ -441,27 +441,27 @@ namespace PdfWriter m_mList.erase(sKey); } } - void CDictObject::Add(const std::string& sKey, const char* sName) + void CDictObject::Add(const std::string& sKey, const char* sName) { Add(sKey, new CNameObject(sName)); } - void CDictObject::Add(const std::string& sKey, int nNumber) + void CDictObject::Add(const std::string& sKey, int nNumber) { Add(sKey, new CNumberObject(nNumber)); } - void CDictObject::Add(const std::string& sKey, unsigned int unNumber) + void CDictObject::Add(const std::string& sKey, unsigned int unNumber) { Add(sKey, (int)unNumber); } - void CDictObject::Add(const std::string& sKey, float fReal) + void CDictObject::Add(const std::string& sKey, float fReal) { Add(sKey, new CRealObject(fReal)); } - void CDictObject::Add(const std::string& sKey, double dReal) + void CDictObject::Add(const std::string& sKey, double dReal) { Add(sKey, new CRealObject(dReal)); } - void CDictObject::Add(const std::string& sKey, bool bBool) + void CDictObject::Add(const std::string& sKey, bool bBool) { Add(sKey, new CBoolObject(bBool)); } @@ -480,7 +480,7 @@ namespace PdfWriter return NULL; } - void CDictObject::WriteToStream(CStream* pStream, CEncrypt* pEncrypt) + void CDictObject::WriteToStream(CStream* pStream, CEncrypt* pEncrypt) { for (auto const &oIter : m_mList) { @@ -501,7 +501,7 @@ namespace PdfWriter } } } - void CDictObject::SetStream(CXref* pXref, CStream* pStream) + void CDictObject::SetStream(CXref* pXref, CStream* pStream) { if (m_pStream) delete m_pStream; @@ -593,7 +593,7 @@ namespace PdfWriter return NULL; } - void CXref::Add(CObjectBase* pObject) + void CXref::Add(CObjectBase* pObject) { if (!pObject) return; @@ -625,7 +625,7 @@ namespace PdfWriter pObject->SetRef(m_unStartOffset + m_arrEntries.size() - 1, pEntry->unGenNo); pObject->SetIndirect(); } - void CXref::WriteTrailer(CStream* pStream) + void CXref::WriteTrailer(CStream* pStream) { unsigned int unMaxObjId = m_arrEntries.size() + m_unStartOffset; @@ -639,7 +639,7 @@ namespace PdfWriter pStream->WriteUInt(m_unAddr); pStream->WriteStr("\012%%EOF\012"); } - void CXref::WriteToStream(CStream* pStream, CEncrypt* pEncrypt) + void CXref::WriteToStream(CStream* pStream, CEncrypt* pEncrypt) { char sBuf[SHORT_BUFFER_SIZE]; char* pBuf; diff --git a/PdfWriter/Src/Pages.cpp b/PdfWriter/Src/Pages.cpp index 0c3f34a724..7840bfb13c 100644 --- a/PdfWriter/Src/Pages.cpp +++ b/PdfWriter/Src/Pages.cpp @@ -238,7 +238,7 @@ namespace PdfWriter pGrState = pPrev; } } - void CPage::SetWidth(double dValue) + void CPage::SetWidth(double dValue) { dValue = std::min(std::max(dValue, 1.0), 14400.0); SetMediaBoxValue(2, dValue); @@ -247,7 +247,7 @@ namespace PdfWriter { return GetMediaBox().fRight; } - void CPage::SetHeight(double dValue) + void CPage::SetHeight(double dValue) { dValue = std::min(std::max(dValue, 1.0), 14400.0); SetMediaBoxValue(3, dValue); @@ -285,7 +285,7 @@ namespace PdfWriter return oMediaBox; } - void CPage::SetMediaBoxValue(unsigned int unIndex, double dValue) + void CPage::SetMediaBoxValue(unsigned int unIndex, double dValue) { CArrayObject* pArray = GetMediaBoxItem(); if (!pArray) @@ -330,7 +330,7 @@ namespace PdfWriter { return Get("Rotate"); } - void CPage::AddResource() + void CPage::AddResource() { CDictObject* pResource = new CDictObject(); if (!pResource) @@ -351,7 +351,7 @@ namespace PdfWriter pProcset->Add(new CNameObject("ImageC")); pProcset->Add(new CNameObject("ImageI")); } - void CPage::BeforeWrite() + void CPage::BeforeWrite() { if (grmode_PATH == m_eGrMode) EndPath(); @@ -364,16 +364,16 @@ namespace PdfWriter GrRestore(); } } - void CPage::SetGrMode(EGrMode eMode) + void CPage::SetGrMode(EGrMode eMode) { m_eGrMode = eMode; // TODO: Сделать проверку плохих ситуаций } - void CPage::CheckGrMode(EGrMode eMode) + void CPage::CheckGrMode(EGrMode eMode) { // TODO: Сделать проверку плохих ситуаций } - void CPage::MoveTo (double dX, double dY) + void CPage::MoveTo (double dX, double dY) { // Operator : m // Description: Начинаем новый subpath, передвигая текущий указатель в точку (x, y)(она же стартовая). @@ -387,7 +387,7 @@ namespace PdfWriter m_oCurPos.Set(dX, dY); m_oStartPos = m_oCurPos; } - void CPage::LineTo (double dX, double dY) + void CPage::LineTo (double dX, double dY) { // Operator : l // Description: Добавляем линию от текущей точки до точки (x, y). Текущую точку выставляем (х, у). @@ -400,7 +400,7 @@ namespace PdfWriter m_oCurPos.Set(dX, dY); } - void CPage::CurveTo(double dX1, double dY1, double dX2, double dY2, double dX3, double dY3) + void CPage::CurveTo(double dX1, double dY1, double dX2, double dY2, double dX3, double dY3) { // Operator : c // Description: Добавляем кривую Безье(кубическую). Начинается кривая в текущей позиции, заканчивается @@ -423,7 +423,7 @@ namespace PdfWriter m_oCurPos.Set(dX3, dY3); } - void CPage::Ellipse(double dX, double dY, double dXRay, double dYRay) + void CPage::Ellipse(double dX, double dY, double dXRay, double dYRay) { SetGrMode(grmode_PATH); @@ -440,7 +440,7 @@ namespace PdfWriter m_oCurPos.Set(dX - dXRay, dY); m_oStartPos = m_oCurPos; } - void CPage::EllipseArc(double dX, double dY, double dXRad, double dYRad, double _dAngle1, double _dAngle2, bool bClockDirection) + void CPage::EllipseArc(double dX, double dY, double dXRad, double dYRad, double _dAngle1, double _dAngle2, bool bClockDirection) { CheckGrMode(grmode_PATH); @@ -505,7 +505,7 @@ namespace PdfWriter m_oCurPos.Set(dEndX, dEndY); m_oStartPos = m_oCurPos; } - void CPage::EllipseArcTo(double dX, double dY, double dXRad, double dYRad, double _dAngle1, double _dAngle2, bool bClockDirection) + void CPage::EllipseArcTo(double dX, double dY, double dXRad, double dYRad, double _dAngle1, double _dAngle2, bool bClockDirection) { // Проверяем эллипс на невырожденность if (dXRad < 0.001 || dYRad < 0.001) @@ -562,7 +562,7 @@ namespace PdfWriter } } } - void CPage::ClosePath() + void CPage::ClosePath() { // Operator : h // Description: Закрываем subpath, соединяя текущую точку с начальной прямой линией. Если subpath @@ -571,7 +571,7 @@ namespace PdfWriter m_pStream->WriteStr("h\012"); m_oCurPos = m_oStartPos; } - void CPage::Stroke() + void CPage::Stroke() { // Operator : S // Description: Обводим path. @@ -580,7 +580,7 @@ namespace PdfWriter m_pStream->WriteStr("S\012"); m_oCurPos.Reset(); } - void CPage::Fill() + void CPage::Fill() { // Operator : f // Description: Заливка path по правилу Nonzero Winding Number Rule(см. спецификацию PDF Part1: PDF 1.7 @@ -589,7 +589,7 @@ namespace PdfWriter m_pStream->WriteStr("f\012"); m_oCurPos.Reset(); } - void CPage::EoFill() + void CPage::EoFill() { // Operator : f* // Description: Заливка path по правилу Even-Odd Rule(см. спецификацию PDF Part1: PDF 1.7 стр. 137, @@ -598,7 +598,7 @@ namespace PdfWriter m_pStream->WriteStr("f*\012"); m_oCurPos.Reset(); } - void CPage::FillStroke() + void CPage::FillStroke() { // Operator : B // Description: Заливка и обоводка path, используя правило для заливки Nonzero Winding Number Rule(см. @@ -609,7 +609,7 @@ namespace PdfWriter m_pStream->WriteStr("B\012"); m_oCurPos.Reset(); } - void CPage::EoFillStroke() + void CPage::EoFillStroke() { // Operator : B* // Description: Заливка и обоводка path, используя правило для заливки Even-Odd Rule(см. @@ -620,7 +620,7 @@ namespace PdfWriter m_pStream->WriteStr("B*\012"); m_oCurPos.Reset(); } - void CPage::EndPath() + void CPage::EndPath() { // Operator : n // Description: Закрываем path, не заливая и не обводя его. Этот оператор используется прежде всего для @@ -629,7 +629,7 @@ namespace PdfWriter m_pStream->WriteStr("n\012"); m_oCurPos.Reset(); } - void CPage::SetLineWidth(double dLineWidth) + void CPage::SetLineWidth(double dLineWidth) { // Operator : w // Descriprion: устанавливаем толщину линии @@ -639,7 +639,7 @@ namespace PdfWriter m_pStream->WriteStr(" w\012"); m_pGrState->m_dLineWidth = dLineWidth; } - void CPage::SetLineCap(ELineCapStyle eLineCap) + void CPage::SetLineCap(ELineCapStyle eLineCap) { // Operator : J // Descriprion: устанавливаем вид окончания линии (LineCapStyle) @@ -649,7 +649,7 @@ namespace PdfWriter m_pStream->WriteStr(" J\012"); m_pGrState->m_eLineCap = eLineCap; } - void CPage::SetLineJoin(ELineJoinStyle eLineJoin) + void CPage::SetLineJoin(ELineJoinStyle eLineJoin) { // Operator : j // Descriprion: устанавливаем вид соединения линий (LineJoinStyle) @@ -658,7 +658,7 @@ namespace PdfWriter m_pStream->WriteStr(" j\012"); m_pGrState->m_eLineJoin = eLineJoin; } - void CPage::SetMiterLimit(double dMiterLimit) + void CPage::SetMiterLimit(double dMiterLimit) { // Operator : M // Descriprion: устанавливаем MiterLimit - константа, относящаяся к виду соединения линий @@ -667,7 +667,7 @@ namespace PdfWriter m_pStream->WriteStr(" M\012"); m_pGrState->m_dMiterLimit = dMiterLimit; } - void CPage::SetDash(const double* pPattern, unsigned int unCount, double dPhase) + void CPage::SetDash(const double* pPattern, unsigned int unCount, double dPhase) { // Operator : d // Descriprion: устанавливаем вид линий (DashMode) @@ -700,7 +700,7 @@ namespace PdfWriter m_pGrState->m_oDashMode.Set(pPattern, unCount, dPhase); } - void CPage::SetFlat(double dFlatness) + void CPage::SetFlat(double dFlatness) { // Operator : i // Descriprion: устанавливаем порог ошибки линии (Flatness tolerance) @@ -709,7 +709,7 @@ namespace PdfWriter m_pStream->WriteStr(" i\012"); m_pGrState->m_dFlatness = dFlatness; } - void CPage::GrSave() + void CPage::GrSave() { // Operator : q // Description: сохраняем текущий GState в графическом стеке @@ -721,7 +721,7 @@ namespace PdfWriter m_pStream->WriteStr("q\012"); m_pGrState = pState; } - void CPage::GrRestore() + void CPage::GrRestore() { // Operator : Q // Description: Восстанавливаем GState, удаляя самый последний GState, и делаем данный GState текущим @@ -736,7 +736,7 @@ namespace PdfWriter m_pStream->WriteStr("Q\012"); } - void CPage::SetStrokeColor(unsigned char unR, unsigned char unG, unsigned char unB) + void CPage::SetStrokeColor(unsigned char unR, unsigned char unG, unsigned char unB) { // Operator : RG // Description: Устанавливаем цветовое пространтсво для обводки в DeviceRGB и устанавливаем цвет для @@ -757,7 +757,7 @@ namespace PdfWriter m_pGrState->m_oStrokeColor.g = dG; m_pGrState->m_oStrokeColor.b = dB; } - void CPage::SetFillColor(unsigned char unR, unsigned char unG, unsigned char unB) + void CPage::SetFillColor(unsigned char unR, unsigned char unG, unsigned char unB) { // Operator : rg // Description: Устанавливаем цветовое пространтсво для заливки в DeviceRGB и устанавливаем цвет для @@ -778,7 +778,7 @@ namespace PdfWriter m_pGrState->m_oFillColor.g = dG; m_pGrState->m_oFillColor.b = dB; } - void CPage::Concat(double dM11, double dM12, double dM21, double dM22, double dX, double dY) + void CPage::Concat(double dM11, double dM12, double dM21, double dM22, double dX, double dY) { // Operator : cm // Description: меняем матрицу преобразований (CTM - Current Transformation Matrix) @@ -806,7 +806,7 @@ namespace PdfWriter m_pGrState->m_oMatrix.x = dX * oCTM.m11 + dY * oCTM.m21 + oCTM.x; m_pGrState->m_oMatrix.y = dX * oCTM.m12 + dY * oCTM.m22 + oCTM.y; } - void CPage::SetTransform(double dM11, double dM12, double dM21, double dM22, double dX, double dY) + void CPage::SetTransform(double dM11, double dM12, double dM21, double dM22, double dX, double dY) { CMatrix oInverse = m_pGrState->m_oMatrix.Inverse(); @@ -821,7 +821,7 @@ namespace PdfWriter if (!oResult.IsIdentity()) Concat(oResult.m11, oResult.m12, oResult.m21, oResult.m22, oResult.x, oResult.y); } - void CPage::Clip() + void CPage::Clip() { // Operator : W // Description: Изменяем текущий clipping path, пересакая его с текущим path, ипользуя правило Nonzero @@ -829,7 +829,7 @@ namespace PdfWriter SetGrMode(grmode_CLIP); m_pStream->WriteStr("W\012"); } - void CPage::Eoclip() + void CPage::Eoclip() { // Operator : W* // Description: Изменяем текущий clipping path, пересакая его с текущим path, ипользуя правило Even-Odd @@ -837,7 +837,7 @@ namespace PdfWriter SetGrMode(grmode_CLIP); m_pStream->WriteStr("W*\012"); } - void CPage::SetExtGrState(CExtGrState* pState) + void CPage::SetExtGrState(CExtGrState* pState) { // Operator : gs // Description: устанавливаем сразу все настройки данного графического состояния(ExtGState) @@ -883,7 +883,7 @@ namespace PdfWriter return sKey; } - void CPage::AddAnnotation(CAnnotation* pAnnot) + void CPage::AddAnnotation(CAnnotation* pAnnot) { CArrayObject* pArray = (CArrayObject*)Get("Annots"); if (!pArray) @@ -897,7 +897,7 @@ namespace PdfWriter return pArray->Add(pAnnot); } - void CPage::BeginText() + void CPage::BeginText() { // Operator : BT // Description: Начало текста @@ -907,7 +907,7 @@ namespace PdfWriter m_oTextPos.Reset(); m_oTextMatrix.Reset(); } - void CPage::EndText() + void CPage::EndText() { // Operator : ET // Description: Окончание текста @@ -915,7 +915,7 @@ namespace PdfWriter m_pStream->WriteStr("ET\012"); SetGrMode(grmode_PAGE); } - void CPage::MoveTextPos(double dX, double dY) + void CPage::MoveTextPos(double dX, double dY) { // Operator : Td // Description: Переходим к началу следующей линии, сдвигаясь от начала текущей на ( fX, fY ). @@ -930,7 +930,7 @@ namespace PdfWriter m_oTextMatrix.y += dX * m_oTextMatrix.m12 + dY * m_oTextMatrix.m22; m_oTextPos.Set(m_oTextMatrix.x, m_oTextMatrix.y); } - void CPage::ShowText(const BYTE* sText, unsigned int unLen) + void CPage::ShowText(const BYTE* sText, unsigned int unLen) { // Operator : Tj // Description: Показать текстовую строку. @@ -938,7 +938,7 @@ namespace PdfWriter WriteText(sText, unLen); m_pStream->WriteStr(" Tj\012"); } - void CPage::WriteText(const BYTE* sText, unsigned int unLen) + void CPage::WriteText(const BYTE* sText, unsigned int unLen) { EFontType eType = m_pFont->GetFontType(); if (fontCIDType0 == eType || fontCIDType0C == eType || fontCIDType0COT == eType || fontCIDType2 == eType || fontCIDType2OT == eType) @@ -952,7 +952,7 @@ namespace PdfWriter m_pStream->WriteEscapeText(sText, unLen); } } - void CPage::DrawText(double dXpos, double dYpos, const BYTE* sText, unsigned int unLen) + void CPage::DrawText(double dXpos, double dYpos, const BYTE* sText, unsigned int unLen) { CheckGrMode(grmode_TEXT); @@ -973,7 +973,7 @@ namespace PdfWriter MoveTextPos(dX, dY); ShowText(sText, unLen); } - void CPage::DrawTextLine(const CTextLine* pTextLine) + void CPage::DrawTextLine(const CTextLine* pTextLine) { if (!pTextLine) return; @@ -1025,7 +1025,7 @@ namespace PdfWriter m_pStream->WriteStr("]TJ\012"); } } - void CPage::SetCharSpace(double dValue) + void CPage::SetCharSpace(double dValue) { // Operator : Tc // Description: Устанавливаем расстояние между буквами @@ -1035,7 +1035,7 @@ namespace PdfWriter m_pStream->WriteReal(dValue); m_pStream->WriteStr(" Tc\012"); } - void CPage::SetHorizontalScalling(double dValue) + void CPage::SetHorizontalScalling(double dValue) { // Operator : Tz // Description: Устанавливаем горизонтальное растяжение/сжатие @@ -1045,7 +1045,7 @@ namespace PdfWriter m_pStream->WriteReal(dValue); m_pStream->WriteStr(" Tz\012"); } - void CPage::SetFontAndSize(CFontDict* pFont, double dSize) + void CPage::SetFontAndSize(CFontDict* pFont, double dSize) { // Operator : Tf // Description: Устанавливаем фонт и размер фонта @@ -1094,7 +1094,7 @@ namespace PdfWriter return sKey; } - void CPage::SetTextRenderingMode(ETextRenderingMode eMode) + void CPage::SetTextRenderingMode(ETextRenderingMode eMode) { // Operator : Tr // Description: Устанавливаем тип закрашивания символов (TextRenderingMode) @@ -1102,7 +1102,7 @@ namespace PdfWriter m_pStream->WriteInt((int)eMode); m_pStream->WriteStr(" Tr\012"); } - void CPage::SetTextMatrix(double dM11, double dM12, double dM21, double dM22, double dX, double dY) + void CPage::SetTextMatrix(double dM11, double dM12, double dM21, double dM22, double dX, double dY) { // Operator : Tm // Description: Устанавливаем матрицу преобразования для текста. @@ -1129,7 +1129,7 @@ namespace PdfWriter m_oTextMatrix.y = dY; m_oTextPos.Set(m_oTextMatrix.x, m_oTextMatrix.y); } - void CPage::ExecuteXObject(CXObject* pXObject) + void CPage::ExecuteXObject(CXObject* pXObject) { const char* sXObjectName = GetXObjectName(pXObject); @@ -1139,7 +1139,7 @@ namespace PdfWriter m_pStream->WriteEscapeName(sXObjectName); m_pStream->WriteStr(" Do\012"); } - void CPage::DrawImage(CImageDict* pImage, double dX, double dY, double dWidth, double dHeight) + void CPage::DrawImage(CImageDict* pImage, double dX, double dY, double dWidth, double dHeight) { GrSave(); Concat(dWidth, 0, 0, dHeight, dX, dY); @@ -1177,7 +1177,7 @@ namespace PdfWriter return sKey; } - void CPage::DrawShading(CShading* pShading) + void CPage::DrawShading(CShading* pShading) { // Operator : sh // Description: отрисовываем градиент @@ -1189,13 +1189,13 @@ namespace PdfWriter m_pStream->WriteEscapeName(sShadingName); m_pStream->WriteStr(" sh\012"); } - void CPage::SetStrokeAlpha(unsigned char unAlpha) + void CPage::SetStrokeAlpha(unsigned char unAlpha) { CExtGrState* pExtGrState = m_pDocument->GetStrokeAlpha((double)(unAlpha / 255.0)); if (pExtGrState) SetExtGrState(pExtGrState); } - void CPage::SetFillAlpha(unsigned char unAlpha) + void CPage::SetFillAlpha(unsigned char unAlpha) { CExtGrState* pExtGrState = m_pDocument->GetFillAlpha((double)(unAlpha / 255.0)); if (pExtGrState) @@ -1263,7 +1263,7 @@ namespace PdfWriter return sKey; } - void CPage::SetPatternColorSpace(CImageTilePattern* pPattern) + void CPage::SetPatternColorSpace(CImageTilePattern* pPattern) { // Operator : csn // Description: задаем паттерн для рисования @@ -1276,7 +1276,7 @@ namespace PdfWriter m_pStream->WriteEscapeName(sPatternName); m_pStream->WriteStr(" scn\012"); } - void CPage::SetFilter(unsigned int unFiler) + void CPage::SetFilter(unsigned int unFiler) { if (m_pContents) m_pContents->SetFilter(unFiler); @@ -1285,7 +1285,7 @@ namespace PdfWriter { return &m_pGrState->m_oMatrix; } - void CPage::AddGroup(CDictObject* pDict) + void CPage::AddGroup(CDictObject* pDict) { Add("Group", pDict); } diff --git a/PdfWriter/Src/Streams.cpp b/PdfWriter/Src/Streams.cpp index 83a3ffc035..4053c77244 100644 --- a/PdfWriter/Src/Streams.cpp +++ b/PdfWriter/Src/Streams.cpp @@ -113,7 +113,7 @@ namespace PdfWriter return (unsigned short)((nChar0 << 8) | nChar1); } - void CStream::Write(const BYTE* pBuffer, unsigned int unSize, bool bCalcCheckSum) + void CStream::Write(const BYTE* pBuffer, unsigned int unSize, bool bCalcCheckSum) { Write(pBuffer, unSize); if (bCalcCheckSum) @@ -123,20 +123,20 @@ namespace PdfWriter m_unCheckSum = oCRC.m_nCRC32; } } - void CStream::WriteChar(char nChar) + void CStream::WriteChar(char nChar) { Write((BYTE*)&nChar, 1); } - void CStream::WriteStr(const char* sString) + void CStream::WriteStr(const char* sString) { unsigned int nLen = StrLen(sString, -1); Write((BYTE*)sString, nLen); } - void CStream::WriteUChar(unsigned char unValue) + void CStream::WriteUChar(unsigned char unValue) { Write(&unValue, 1); } - void CStream::WriteInt(int nValue) + void CStream::WriteInt(int nValue) { //int nLen = 0; //const char* sString = NSFastIntToString::GetString(fabs(nValue), nLen); @@ -155,11 +155,11 @@ namespace PdfWriter return WriteStr(pBuffer); //} } - void CStream::WriteUInt(unsigned int unValue) + void CStream::WriteUInt(unsigned int unValue) { WriteInt((int)unValue); } - void CStream::WriteHex(int nValue, int nLen) + void CStream::WriteHex(int nValue, int nLen) { if (2 == nLen) Write((const BYTE*)c_pHexStrings[(unsigned char)nValue], 2); @@ -169,14 +169,14 @@ namespace PdfWriter Write((const BYTE*)c_pHexStrings[(unsigned char)nValue], 2); } } - void CStream::WriteReal(float fValue) + void CStream::WriteReal(float fValue) { char pBuffer[32]; memset(pBuffer, 0x00, 32); FtoA(pBuffer, fValue, pBuffer + 31); return WriteStr(pBuffer); } - void CStream::WriteReal(double dValue) + void CStream::WriteReal(double dValue) { //int nIVal = (int)dValue; //int nFVal = (int)(fabs(dValue - nIVal) * 10000); @@ -236,7 +236,7 @@ namespace PdfWriter FtoA(pBuffer, dValue, pBuffer + 31); return WriteStr(pBuffer); } - void CStream::WriteEscapeName(const char* sValue) + void CStream::WriteEscapeName(const char* sValue) { char sTmpChar[LIMIT_MAX_NAME_LEN * 3 + 2]; @@ -281,7 +281,7 @@ namespace PdfWriter Write((BYTE*)sTmpChar, StrLen(sTmpChar, -1)); } - void CStream::WriteEscapeText(const BYTE* sText, unsigned int unLen) + void CStream::WriteEscapeText(const BYTE* sText, unsigned int unLen) { if (!unLen || !sText) return; @@ -325,7 +325,7 @@ namespace PdfWriter Write((BYTE*)sBuf, nIndex); } - void CStream::WriteBinary(const BYTE* pData, unsigned int unLen, CEncrypt* pEncrypt) + void CStream::WriteBinary(const BYTE* pData, unsigned int unLen, CEncrypt* pEncrypt) { char sBuf[TEXT_DEFAULT_LEN]; @@ -338,7 +338,7 @@ namespace PdfWriter { pBuf = new BYTE[unLen]; bDelete = true; - pEncrypt->CryptBuf(pData, pBuf, unLen); + pEncrypt->CryptBuf(pData, pBuf, unLen, true); pBuffer = pBuf; } else @@ -359,7 +359,7 @@ namespace PdfWriter if (bDelete) delete[] pBuf; } - void CStream::WriteStreamWithDeflate(CStream* pStream, CEncrypt* pEncrypt) + void CStream::WriteStreamWithDeflate(CStream* pStream, CEncrypt* pEncrypt) { unsigned long nRet = OK; @@ -394,7 +394,7 @@ namespace PdfWriter { if (pEncrypt) { - pEncrypt->CryptBuf(otbuf, ebuf, DEFLATE_BUF_SIZ); + pEncrypt->CryptBuf(otbuf, ebuf, DEFLATE_BUF_SIZ, false); Write(ebuf, DEFLATE_BUF_SIZ); } else @@ -423,7 +423,7 @@ namespace PdfWriter unsigned int osize = DEFLATE_BUF_SIZ - ZStream.GetAvailOut(); if (pEncrypt) { - pEncrypt->CryptBuf(otbuf, ebuf, osize); + pEncrypt->CryptBuf(otbuf, ebuf, osize, true); Write(ebuf, osize); } else @@ -438,7 +438,7 @@ namespace PdfWriter ZStream.End(); } - void CStream::WriteStream(CStream* pStream, unsigned int unFilter, CEncrypt *pEncrypt) + void CStream::WriteStream(CStream* pStream, unsigned int unFilter, CEncrypt *pEncrypt) { if (pStream->Size() <= 0) return; @@ -464,7 +464,7 @@ namespace PdfWriter if (pEncrypt) { - pEncrypt->CryptBuf(pBuf, pEBuf, unSize); + pEncrypt->CryptBuf(pBuf, pEBuf, unSize, pStream->IsEof()); Write(pEBuf, unSize); } else @@ -473,29 +473,29 @@ namespace PdfWriter } } } - void CStream::Write(CNullObject* pNull) + void CStream::Write(CNullObject* pNull) { } - void CStream::Write(CBoolObject* pBool) + void CStream::Write(CBoolObject* pBool) { if (pBool->Get()) WriteStr("true"); else WriteStr("false"); } - void CStream::Write(CNumberObject* pNumber) + void CStream::Write(CNumberObject* pNumber) { WriteInt(pNumber->Get()); } - void CStream::Write(CRealObject* pReal) + void CStream::Write(CRealObject* pReal) { WriteReal(pReal->Get()); } - void CStream::Write(CNameObject* pName) + void CStream::Write(CNameObject* pName) { WriteEscapeName(pName->Get()); } - void CStream::Write(CStringObject* pString, CEncrypt* pEncrypt) + void CStream::Write(CStringObject* pString, CEncrypt* pEncrypt) { if (pEncrypt) pEncrypt->Reset(); @@ -512,7 +512,7 @@ namespace PdfWriter WriteEscapeText(pString->GetString(), pString->GetLength()); } } - void CStream::Write(CBinaryObject* pBinary, CEncrypt* pEncrypt) + void CStream::Write(CBinaryObject* pBinary, CEncrypt* pEncrypt) { unsigned int unLen = pBinary->GetLength(); BYTE* pValue = pBinary->GetValue(); @@ -527,7 +527,7 @@ namespace PdfWriter WriteBinary(pValue, unLen, pEncrypt); WriteChar('>'); } - void CStream::Write(CArrayObject* pArray, CEncrypt* pEncrypt) + void CStream::Write(CArrayObject* pArray, CEncrypt* pEncrypt) { WriteStr("[ "); for (int nIndex = 0, nCount = pArray->GetCount(); nIndex < nCount; nIndex++) @@ -538,7 +538,7 @@ namespace PdfWriter } WriteChar(']'); } - void CStream::Write(CDictObject* pDict, CEncrypt* pEncrypt) + void CStream::Write(CDictObject* pDict, CEncrypt* pEncrypt) { WriteStr("<<\012"); @@ -637,7 +637,7 @@ namespace PdfWriter pDict->AfterWrite(); } - void CStream::Write(CObjectBase* pObject, CEncrypt* pEncrypt) + void CStream::Write(CObjectBase* pObject, CEncrypt* pEncrypt) { if (pObject) { diff --git a/PdfWriter/Src/Types.h b/PdfWriter/Src/Types.h index 03fe841b30..717c5308d2 100644 --- a/PdfWriter/Src/Types.h +++ b/PdfWriter/Src/Types.h @@ -52,11 +52,6 @@ namespace PdfWriter { - enum EEncryptMode - { - encryptmode_R2 = 2, - encryptmode_R3 = 3 - }; struct TRect { TRect() diff --git a/UnicodeConverter/UnicodeConverter.cpp b/UnicodeConverter/UnicodeConverter.cpp index 627ef2d63f..aa97926867 100644 --- a/UnicodeConverter/UnicodeConverter.cpp +++ b/UnicodeConverter/UnicodeConverter.cpp @@ -103,31 +103,27 @@ namespace NSUnicodeConverter int32_t nOutputLen = nUCharLength * 2; if (U_SUCCESS(status)) { - UChar* pOutput = new UChar[nOutputLen * sizeof(UChar)]; - nOutputLen = usprep_prepare(profile, pUCharStart, nUCharLength, pOutput, nInputLen, 0, &parseError, &status ); + UChar* pOutput = new UChar[nOutputLen * sizeof(UChar) * 3]; + nOutputLen = usprep_prepare(profile, pUCharStart, nUCharLength, pOutput, nOutputLen, 0, &parseError, &status ); - if (U_SUCCESS(status)) - { + if (U_SUCCESS(status)) + { UConverter* conv = ucnv_open("UTF-8", &status); if (U_SUCCESS(status)) { const UChar* pOutputLimit = pOutput + nOutputLen; const UChar* pOutputStart = pOutput; - sRes.resize(nOutputLen * ucnv_getMaxCharSize(conv));// UTF-16 uses 2 code-points per char - char *sResStart = &sRes[0]; + char *sResStart = new char[nOutputLen * ucnv_getMaxCharSize(conv)]; char *sResCur = sResStart; - const char *sResLimit = sResCur + sRes.size(); + const char *sResLimit = sResCur + nOutputLen * ucnv_getMaxCharSize(conv); ucnv_fromUnicode(conv, &sResCur, sResLimit, &pOutputStart, pOutputLimit, NULL, TRUE, &status); if (U_SUCCESS(status)) { - sRes.resize(sResCur - sResStart); - } - else - { - sRes.clear(); + sRes = std::string(sResStart, sResCur - sResStart); } + delete sResStart; ucnv_close(conv); } }