├── CacheCryptoAPI.opensdf ├── ISCAPI ├── ISCAPI.h ├── iscapi.def ├── app.rc ├── app.ico ├── resource.h ├── ISCAPI.vcxproj.user ├── Stdafx.h ├── Stdafx.cpp ├── AssemblyInfo.cpp ├── ReadMe.txt ├── ISCAPI.vcxproj.filters ├── ISCAPI.cpp └── ISCAPI.vcxproj ├── ReadMe.txt ├── QuickStart.txt ├── CacheCryptoAPI.suo ├── CacheCryptoAPI ├── app.ico ├── app.rc ├── resource.h ├── CacheCryptoAPI.suo ├── Stdafx.h ├── Stdafx.cpp ├── CacheCryptoAPI.vcxproj.user ├── AssemblyInfo.cpp ├── ReadMe.txt ├── CacheCryptoAPI.vcxproj.filters ├── CacheLogger.h ├── CacheLogger.cpp ├── CacheCryptoAPI.h ├── CacheCryptoAPI.vcxproj └── CacheCryptoAPI.cpp ├── CacheCryptoConsole ├── app.rc ├── app.ico ├── resource.h ├── CacheCryptoConsole.vcxproj.user ├── stdafx.cpp ├── stdafx.h ├── AssemblyInfo.cpp ├── ReadMe.txt ├── CacheCryptoConsole.vcxproj.filters ├── CacheCryptoConsole.vcxproj └── CacheCryptoConsole.cpp ├── CacheCryptoAPI.sln └── iscapi.xml /CacheCryptoAPI.opensdf: -------------------------------------------------------------------------------- 1 | ArtemARTEM -------------------------------------------------------------------------------- /ISCAPI/ISCAPI.h: -------------------------------------------------------------------------------- 1 | // ISCAPI.h 2 | #pragma once 3 | -------------------------------------------------------------------------------- /ISCAPI/iscapi.def: -------------------------------------------------------------------------------- 1 | LIBRARY iscapi 2 | EXPORTS 3 | GetZFTable @1 -------------------------------------------------------------------------------- /ReadMe.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/intersystems-community/CacheCrypto/master/ReadMe.txt -------------------------------------------------------------------------------- /ISCAPI/app.rc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/intersystems-community/CacheCrypto/master/ISCAPI/app.rc -------------------------------------------------------------------------------- /ISCAPI/app.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/intersystems-community/CacheCrypto/master/ISCAPI/app.ico -------------------------------------------------------------------------------- /QuickStart.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/intersystems-community/CacheCrypto/master/QuickStart.txt -------------------------------------------------------------------------------- /CacheCryptoAPI.suo: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/intersystems-community/CacheCrypto/master/CacheCryptoAPI.suo -------------------------------------------------------------------------------- /CacheCryptoAPI/app.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/intersystems-community/CacheCrypto/master/CacheCryptoAPI/app.ico -------------------------------------------------------------------------------- /CacheCryptoAPI/app.rc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/intersystems-community/CacheCrypto/master/CacheCryptoAPI/app.rc -------------------------------------------------------------------------------- /ISCAPI/resource.h: -------------------------------------------------------------------------------- 1 | //{{NO_DEPENDENCIES}} 2 | // Microsoft Visual C++ generated include file. 3 | // Used by app.rc 4 | -------------------------------------------------------------------------------- /CacheCryptoConsole/app.rc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/intersystems-community/CacheCrypto/master/CacheCryptoConsole/app.rc -------------------------------------------------------------------------------- /CacheCryptoAPI/resource.h: -------------------------------------------------------------------------------- 1 | //{{NO_DEPENDENCIES}} 2 | // Microsoft Visual C++ generated include file. 3 | // Used by app.rc 4 | -------------------------------------------------------------------------------- /CacheCryptoConsole/app.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/intersystems-community/CacheCrypto/master/CacheCryptoConsole/app.ico -------------------------------------------------------------------------------- /CacheCryptoConsole/resource.h: -------------------------------------------------------------------------------- 1 | //{{NO_DEPENDENCIES}} 2 | // Microsoft Visual C++ generated include file. 3 | // Used by app.rc 4 | -------------------------------------------------------------------------------- /CacheCryptoAPI/CacheCryptoAPI.suo: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/intersystems-community/CacheCrypto/master/CacheCryptoAPI/CacheCryptoAPI.suo -------------------------------------------------------------------------------- /ISCAPI/ISCAPI.vcxproj.user: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /CacheCryptoConsole/CacheCryptoConsole.vcxproj.user: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /ISCAPI/Stdafx.h: -------------------------------------------------------------------------------- 1 | // stdafx.h : include file for standard system include files, 2 | // or project specific include files that are used frequently, 3 | // but are changed infrequently 4 | 5 | #pragma once 6 | 7 | 8 | -------------------------------------------------------------------------------- /CacheCryptoAPI/Stdafx.h: -------------------------------------------------------------------------------- 1 | // stdafx.h : include file for standard system include files, 2 | // or project specific include files that are used frequently, 3 | // but are changed infrequently 4 | 5 | #pragma once 6 | 7 | 8 | -------------------------------------------------------------------------------- /ISCAPI/Stdafx.cpp: -------------------------------------------------------------------------------- 1 | // stdafx.cpp : source file that includes just the standard includes 2 | // ISCAPI.pch will be the pre-compiled header 3 | // stdafx.obj will contain the pre-compiled type information 4 | 5 | #include "stdafx.h" 6 | -------------------------------------------------------------------------------- /CacheCryptoAPI/Stdafx.cpp: -------------------------------------------------------------------------------- 1 | // stdafx.cpp : source file that includes just the standard includes 2 | // CacheCryptoAPI.pch will be the pre-compiled header 3 | // stdafx.obj will contain the pre-compiled type information 4 | 5 | #include "stdafx.h" 6 | -------------------------------------------------------------------------------- /CacheCryptoConsole/stdafx.cpp: -------------------------------------------------------------------------------- 1 | // stdafx.cpp : source file that includes just the standard includes 2 | // CacheCryptoConsole.pch will be the pre-compiled header 3 | // stdafx.obj will contain the pre-compiled type information 4 | 5 | #include "stdafx.h" 6 | 7 | 8 | -------------------------------------------------------------------------------- /CacheCryptoConsole/stdafx.h: -------------------------------------------------------------------------------- 1 | // stdafx.h : include file for standard system include files, 2 | // or project specific include files that are used frequently, but 3 | // are changed infrequently 4 | // 5 | 6 | #pragma once 7 | 8 | // TODO: reference additional headers your program requires here 9 | -------------------------------------------------------------------------------- /CacheCryptoAPI/CacheCryptoAPI.vcxproj.user: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | $(ProjectDir) 5 | WindowsLocalDebugger 6 | 7 | -------------------------------------------------------------------------------- /ISCAPI/AssemblyInfo.cpp: -------------------------------------------------------------------------------- 1 | #include "stdafx.h" 2 | 3 | using namespace System; 4 | using namespace System::Reflection; 5 | using namespace System::Runtime::CompilerServices; 6 | using namespace System::Runtime::InteropServices; 7 | using namespace System::Security::Permissions; 8 | 9 | // 10 | // General Information about an assembly is controlled through the following 11 | // set of attributes. Change these attribute values to modify the information 12 | // associated with an assembly. 13 | // 14 | [assembly:AssemblyTitleAttribute("ISCAPI")]; 15 | [assembly:AssemblyDescriptionAttribute("")]; 16 | [assembly:AssemblyConfigurationAttribute("")]; 17 | [assembly:AssemblyCompanyAttribute("")]; 18 | [assembly:AssemblyProductAttribute("ISCAPI")]; 19 | [assembly:AssemblyCopyrightAttribute("Copyright (c) 2013")]; 20 | [assembly:AssemblyTrademarkAttribute("")]; 21 | [assembly:AssemblyCultureAttribute("")]; 22 | 23 | // 24 | // Version information for an assembly consists of the following four values: 25 | // 26 | // Major Version 27 | // Minor Version 28 | // Build Number 29 | // Revision 30 | // 31 | // You can specify all the value or you can default the Revision and Build Numbers 32 | // by using the '*' as shown below: 33 | 34 | [assembly:AssemblyVersionAttribute("1.0.*")]; 35 | 36 | [assembly:ComVisible(false)]; 37 | 38 | [assembly:CLSCompliantAttribute(true)]; 39 | 40 | [assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)]; 41 | -------------------------------------------------------------------------------- /CacheCryptoAPI/AssemblyInfo.cpp: -------------------------------------------------------------------------------- 1 | #include "stdafx.h" 2 | 3 | using namespace System; 4 | using namespace System::Reflection; 5 | using namespace System::Runtime::CompilerServices; 6 | using namespace System::Runtime::InteropServices; 7 | using namespace System::Security::Permissions; 8 | 9 | // 10 | // General Information about an assembly is controlled through the following 11 | // set of attributes. Change these attribute values to modify the information 12 | // associated with an assembly. 13 | // 14 | [assembly:AssemblyTitleAttribute("CacheCryptoAPI")]; 15 | [assembly:AssemblyDescriptionAttribute("")]; 16 | [assembly:AssemblyConfigurationAttribute("")]; 17 | [assembly:AssemblyCompanyAttribute("")]; 18 | [assembly:AssemblyProductAttribute("CacheCryptoAPI")]; 19 | [assembly:AssemblyCopyrightAttribute("Copyright (c) 2013")]; 20 | [assembly:AssemblyTrademarkAttribute("")]; 21 | [assembly:AssemblyCultureAttribute("")]; 22 | 23 | // 24 | // Version information for an assembly consists of the following four values: 25 | // 26 | // Major Version 27 | // Minor Version 28 | // Build Number 29 | // Revision 30 | // 31 | // You can specify all the value or you can default the Revision and Build Numbers 32 | // by using the '*' as shown below: 33 | 34 | [assembly:AssemblyVersionAttribute("1.0.*")]; 35 | 36 | [assembly:ComVisible(false)]; 37 | 38 | [assembly:CLSCompliantAttribute(true)]; 39 | 40 | [assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)]; 41 | -------------------------------------------------------------------------------- /CacheCryptoConsole/AssemblyInfo.cpp: -------------------------------------------------------------------------------- 1 | #include "stdafx.h" 2 | 3 | using namespace System; 4 | using namespace System::Reflection; 5 | using namespace System::Runtime::CompilerServices; 6 | using namespace System::Runtime::InteropServices; 7 | using namespace System::Security::Permissions; 8 | 9 | // 10 | // General Information about an assembly is controlled through the following 11 | // set of attributes. Change these attribute values to modify the information 12 | // associated with an assembly. 13 | // 14 | [assembly:AssemblyTitleAttribute("CacheCryptoConsole")]; 15 | [assembly:AssemblyDescriptionAttribute("")]; 16 | [assembly:AssemblyConfigurationAttribute("")]; 17 | [assembly:AssemblyCompanyAttribute("")]; 18 | [assembly:AssemblyProductAttribute("CacheCryptoConsole")]; 19 | [assembly:AssemblyCopyrightAttribute("Copyright (c) 2013")]; 20 | [assembly:AssemblyTrademarkAttribute("")]; 21 | [assembly:AssemblyCultureAttribute("")]; 22 | 23 | // 24 | // Version information for an assembly consists of the following four values: 25 | // 26 | // Major Version 27 | // Minor Version 28 | // Build Number 29 | // Revision 30 | // 31 | // You can specify all the value or you can default the Revision and Build Numbers 32 | // by using the '*' as shown below: 33 | 34 | [assembly:AssemblyVersionAttribute("1.0.*")]; 35 | 36 | [assembly:ComVisible(false)]; 37 | 38 | [assembly:CLSCompliantAttribute(true)]; 39 | 40 | [assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)]; 41 | -------------------------------------------------------------------------------- /ISCAPI/ReadMe.txt: -------------------------------------------------------------------------------- 1 | ======================================================================== 2 | DYNAMIC LINK LIBRARY : ISCAPI Project Overview 3 | ======================================================================== 4 | 5 | AppWizard has created this ISCAPI DLL for you. 6 | 7 | This file contains a summary of what you will find in each of the files that 8 | make up your ISCAPI application. 9 | 10 | ISCAPI.vcxproj 11 | This is the main project file for VC++ projects generated using an Application Wizard. 12 | It contains information about the version of Visual C++ that generated the file, and 13 | information about the platforms, configurations, and project features selected with the 14 | Application Wizard. 15 | 16 | ISCAPI.vcxproj.filters 17 | This is the filters file for VC++ projects generated using an Application Wizard. 18 | It contains information about the association between the files in your project 19 | and the filters. This association is used in the IDE to show grouping of files with 20 | similar extensions under a specific node (for e.g. ".cpp" files are associated with the 21 | "Source Files" filter). 22 | 23 | ISCAPI.cpp 24 | This is the main DLL source file. 25 | 26 | ISCAPI.h 27 | This file contains a class declaration. 28 | 29 | AssemblyInfo.cpp 30 | Contains custom attributes for modifying assembly metadata. 31 | 32 | ///////////////////////////////////////////////////////////////////////////// 33 | Other notes: 34 | 35 | AppWizard uses "TODO:" to indicate parts of the source code you 36 | should add to or customize. 37 | 38 | ///////////////////////////////////////////////////////////////////////////// 39 | -------------------------------------------------------------------------------- /CacheCryptoConsole/ReadMe.txt: -------------------------------------------------------------------------------- 1 | ======================================================================== 2 | APPLICATION : CacheCryptoConsole Project Overview 3 | ======================================================================== 4 | 5 | AppWizard has created this CacheCryptoConsole Application for you. 6 | 7 | This file contains a summary of what you will find in each of the files that 8 | make up your CacheCryptoConsole application. 9 | 10 | CacheCryptoConsole.vcxproj 11 | This is the main project file for VC++ projects generated using an Application Wizard. 12 | It contains information about the version of Visual C++ that generated the file, and 13 | information about the platforms, configurations, and project features selected with the 14 | Application Wizard. 15 | 16 | CacheCryptoConsole.vcxproj.filters 17 | This is the filters file for VC++ projects generated using an Application Wizard. 18 | It contains information about the association between the files in your project 19 | and the filters. This association is used in the IDE to show grouping of files with 20 | similar extensions under a specific node (for e.g. ".cpp" files are associated with the 21 | "Source Files" filter). 22 | 23 | CacheCryptoConsole.cpp 24 | This is the main application source file. 25 | 26 | AssemblyInfo.cpp 27 | Contains custom attributes for modifying assembly metadata. 28 | 29 | ///////////////////////////////////////////////////////////////////////////// 30 | Other notes: 31 | 32 | AppWizard uses "TODO:" to indicate parts of the source code you 33 | should add to or customize. 34 | 35 | ///////////////////////////////////////////////////////////////////////////// 36 | -------------------------------------------------------------------------------- /CacheCryptoAPI/ReadMe.txt: -------------------------------------------------------------------------------- 1 | ======================================================================== 2 | DYNAMIC LINK LIBRARY : CacheCryptoAPI Project Overview 3 | ======================================================================== 4 | 5 | AppWizard has created this CacheCryptoAPI DLL for you. 6 | 7 | This file contains a summary of what you will find in each of the files that 8 | make up your CacheCryptoAPI application. 9 | 10 | CacheCryptoAPI.vcxproj 11 | This is the main project file for VC++ projects generated using an Application Wizard. 12 | It contains information about the version of Visual C++ that generated the file, and 13 | information about the platforms, configurations, and project features selected with the 14 | Application Wizard. 15 | 16 | CacheCryptoAPI.vcxproj.filters 17 | This is the filters file for VC++ projects generated using an Application Wizard. 18 | It contains information about the association between the files in your project 19 | and the filters. This association is used in the IDE to show grouping of files with 20 | similar extensions under a specific node (for e.g. ".cpp" files are associated with the 21 | "Source Files" filter). 22 | 23 | CacheCryptoAPI.cpp 24 | This is the main DLL source file. 25 | 26 | CacheCryptoAPI.h 27 | This file contains a class declaration. 28 | 29 | AssemblyInfo.cpp 30 | Contains custom attributes for modifying assembly metadata. 31 | 32 | ///////////////////////////////////////////////////////////////////////////// 33 | Other notes: 34 | 35 | AppWizard uses "TODO:" to indicate parts of the source code you 36 | should add to or customize. 37 | 38 | ///////////////////////////////////////////////////////////////////////////// 39 | -------------------------------------------------------------------------------- /CacheCryptoConsole/CacheCryptoConsole.vcxproj.filters: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | 20 | Resource Files 21 | 22 | 23 | 24 | 25 | Header Files 26 | 27 | 28 | Header Files 29 | 30 | 31 | 32 | 33 | Resource Files 34 | 35 | 36 | 37 | 38 | Source Files 39 | 40 | 41 | Source Files 42 | 43 | 44 | Source Files 45 | 46 | 47 | -------------------------------------------------------------------------------- /ISCAPI/ISCAPI.vcxproj.filters: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Header Files 20 | 21 | 22 | Header Files 23 | 24 | 25 | Header Files 26 | 27 | 28 | 29 | 30 | Source Files 31 | 32 | 33 | Source Files 34 | 35 | 36 | Source Files 37 | 38 | 39 | 40 | 41 | 42 | Resource Files 43 | 44 | 45 | Source Files 46 | 47 | 48 | 49 | 50 | Resource Files 51 | 52 | 53 | -------------------------------------------------------------------------------- /CacheCryptoAPI/CacheCryptoAPI.vcxproj.filters: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Header Files 20 | 21 | 22 | Header Files 23 | 24 | 25 | Header Files 26 | 27 | 28 | Header Files 29 | 30 | 31 | 32 | 33 | Source Files 34 | 35 | 36 | Source Files 37 | 38 | 39 | Source Files 40 | 41 | 42 | Source Files 43 | 44 | 45 | 46 | 47 | 48 | Resource Files 49 | 50 | 51 | 52 | 53 | Resource Files 54 | 55 | 56 | -------------------------------------------------------------------------------- /CacheCryptoAPI/CacheLogger.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | // Constants define the level of details in logs 12 | #define LOGLEVELNONE 0 // no logs 13 | #define LOGLEVELERR 1 // errors only 14 | #define LOGLEVELALL 2 // log everithing 15 | 16 | #define LOGLEVELDEFAULT LOGLEVELALL 17 | #define LOGFILENAME L"C:\\CacheCrypto.log" 18 | 19 | // Constants define destination of program output 20 | #define LOGTARGETFILE 1 // logfile 21 | #define LOGTARGETCONSOLE 2 // console 22 | 23 | // Basic class, provides logging functions 24 | class CacheLogger 25 | { 26 | 27 | private: 28 | wchar_t * LogFileName; // name of log file 29 | int LogLevel; // level of details in log messages, used with constants LOGLEVELNONE, LOGLEVELERR, LOGLEVELALL 30 | int LogSourceLocation; // shows what file and line in file initiated call, for debugging purposes 31 | int LogTargets; // defines destination of logging actions: to file with LOGTARGETFILE or(and) to console LOGTARGETCONSOLE 32 | 33 | public: 34 | CacheLogger(void); // basic class constructor 35 | ~CacheLogger(void); // basic class destructor 36 | 37 | void logMessage(wchar_t* msg, int level, char* FFUNCTION, char* FFILE, int FLINE); // function log messages, applies all options in parameters. Used via macros LogMessage(msg) 38 | void logMessage(wchar_t* msg); // function log messages 39 | 40 | int setLogFileName(wchar_t* fn); // set value to LogFileName 41 | int setLogTargets(int targets); // set value to LogTargets 42 | int setLogLevel(int logLevel); // set value to LogLevel 43 | int setLogSourceLocation(int flag); // set value to LogSourceLocation 44 | 45 | void logMessageToFile(wchar_t* msg); // output message to file 46 | void logMessageToConsole(wchar_t* msg); // output message to console windpe as it is, checking the LogTargets 47 | void consoleMessage(wchar_t * msg); // output message to console windpe as it is, anyway 48 | 49 | wchar_t* getLastErrorCode(); // write code of last occured error 50 | wchar_t* getLastErrorMsg(); // write text of last error 51 | void logLastError(); // write both code and last error text 52 | void logError(wchar_t * msg); 53 | 54 | }; 55 | 56 | -------------------------------------------------------------------------------- /CacheCryptoAPI.sln: -------------------------------------------------------------------------------- 1 | Microsoft Visual Studio Solution File, Format Version 11.00 2 | # Visual Studio 2010 3 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CacheCryptoAPI", "CacheCryptoAPI\CacheCryptoAPI.vcxproj", "{2977F54B-E87B-48DA-BA5B-7584942AD76F}" 4 | EndProject 5 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CacheCryptoConsole", "CacheCryptoConsole\CacheCryptoConsole.vcxproj", "{4616D38F-98F0-4D47-9698-8A01F50E11BE}" 6 | ProjectSection(ProjectDependencies) = postProject 7 | {2977F54B-E87B-48DA-BA5B-7584942AD76F} = {2977F54B-E87B-48DA-BA5B-7584942AD76F} 8 | EndProjectSection 9 | EndProject 10 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ISCAPI", "ISCAPI\ISCAPI.vcxproj", "{78B87F2F-299B-4C6C-B76B-7070F34C02E0}" 11 | ProjectSection(ProjectDependencies) = postProject 12 | {2977F54B-E87B-48DA-BA5B-7584942AD76F} = {2977F54B-E87B-48DA-BA5B-7584942AD76F} 13 | EndProjectSection 14 | EndProject 15 | Global 16 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 17 | Debug|Win32 = Debug|Win32 18 | Debug|x64 = Debug|x64 19 | Release|Win32 = Release|Win32 20 | Release|x64 = Release|x64 21 | EndGlobalSection 22 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 23 | {2977F54B-E87B-48DA-BA5B-7584942AD76F}.Debug|Win32.ActiveCfg = Debug|x64 24 | {2977F54B-E87B-48DA-BA5B-7584942AD76F}.Debug|Win32.Build.0 = Debug|x64 25 | {2977F54B-E87B-48DA-BA5B-7584942AD76F}.Debug|x64.ActiveCfg = Debug|x64 26 | {2977F54B-E87B-48DA-BA5B-7584942AD76F}.Debug|x64.Build.0 = Debug|x64 27 | {2977F54B-E87B-48DA-BA5B-7584942AD76F}.Release|Win32.ActiveCfg = Release|Win32 28 | {2977F54B-E87B-48DA-BA5B-7584942AD76F}.Release|x64.ActiveCfg = Release|Win32 29 | {2977F54B-E87B-48DA-BA5B-7584942AD76F}.Release|x64.Build.0 = Release|Win32 30 | {4616D38F-98F0-4D47-9698-8A01F50E11BE}.Debug|Win32.ActiveCfg = Debug|Win32 31 | {4616D38F-98F0-4D47-9698-8A01F50E11BE}.Debug|Win32.Build.0 = Debug|Win32 32 | {4616D38F-98F0-4D47-9698-8A01F50E11BE}.Debug|x64.ActiveCfg = Debug|x64 33 | {4616D38F-98F0-4D47-9698-8A01F50E11BE}.Release|Win32.ActiveCfg = Release|Win32 34 | {4616D38F-98F0-4D47-9698-8A01F50E11BE}.Release|Win32.Build.0 = Release|Win32 35 | {4616D38F-98F0-4D47-9698-8A01F50E11BE}.Release|x64.ActiveCfg = Release|Win32 36 | {78B87F2F-299B-4C6C-B76B-7070F34C02E0}.Debug|Win32.ActiveCfg = Debug|Win32 37 | {78B87F2F-299B-4C6C-B76B-7070F34C02E0}.Debug|Win32.Build.0 = Debug|Win32 38 | {78B87F2F-299B-4C6C-B76B-7070F34C02E0}.Debug|x64.ActiveCfg = Debug|x64 39 | {78B87F2F-299B-4C6C-B76B-7070F34C02E0}.Release|Win32.ActiveCfg = Release|Win32 40 | {78B87F2F-299B-4C6C-B76B-7070F34C02E0}.Release|Win32.Build.0 = Release|Win32 41 | {78B87F2F-299B-4C6C-B76B-7070F34C02E0}.Release|x64.ActiveCfg = Release|Win32 42 | EndGlobalSection 43 | GlobalSection(SolutionProperties) = preSolution 44 | HideSolutionNode = FALSE 45 | EndGlobalSection 46 | EndGlobal 47 | -------------------------------------------------------------------------------- /CacheCryptoAPI/CacheLogger.cpp: -------------------------------------------------------------------------------- 1 | #include "StdAfx.h" 2 | #include "CacheLogger.h" 3 | 4 | #define LogMessage(msg) logMessage(msg, LOGLEVELDEFAULT, __FUNCTION__, __FILE__, __LINE__) 5 | 6 | CacheLogger::CacheLogger(void) 7 | { 8 | wchar_t * LogFileName = LOGFILENAME; 9 | int LogLevel = LOGLEVELDEFAULT; 10 | int LogSourceLocation = 1; 11 | int LogTargets = LOGTARGETFILE | LOGTARGETCONSOLE; 12 | } 13 | //================================================================================================= 14 | CacheLogger::~CacheLogger(void) 15 | { 16 | if (LogFileName) 17 | delete[] LogFileName; 18 | } 19 | //================================================================================================= 20 | int CacheLogger::setLogFileName(wchar_t* fn) { 21 | LogFileName = _wcsdup(fn); 22 | return 0; 23 | } 24 | //================================================================================================= 25 | int CacheLogger::setLogTargets(int targets) { 26 | LogTargets = targets; 27 | return 0; 28 | } 29 | //================================================================================================= 30 | int CacheLogger::setLogLevel(int logLevel) { 31 | LogLevel = logLevel; 32 | return 0; 33 | } 34 | //================================================================================================= 35 | int CacheLogger::setLogSourceLocation(int flag) { 36 | LogSourceLocation = flag; 37 | return 0; 38 | } 39 | //================================================================================================= 40 | void CacheLogger::logMessageToFile(wchar_t* msg) { 41 | FILE *fd = NULL; 42 | if (! (LogTargets & LOGTARGETFILE)) return; 43 | if ((fd = _wfopen(LogFileName, L"a,ccs=UTF-8")) == NULL) { 44 | wprintf(L"Error opening logfile: %s", LogFileName); 45 | return; 46 | } 47 | else { 48 | fwprintf(fd, L"%s\n", msg); 49 | } 50 | fflush(fd); 51 | fclose(fd); 52 | } 53 | //================================================================================================= 54 | void CacheLogger::logMessageToConsole(wchar_t* msg) { 55 | if (LogTargets & LOGTARGETCONSOLE) wprintf (L"%s\n", msg); 56 | } 57 | //================================================================================================= 58 | void CacheLogger::logMessage(wchar_t* msg, int level, char* FFUNCTION, char* FFILE, int FLINE) { 59 | wchar_t dtBuf[1024]; 60 | struct tm lNow; 61 | time_t lTime; 62 | 63 | if (level > LogLevel) return; 64 | 65 | time(&lTime); 66 | localtime_s(&lNow, &lTime); 67 | wcsftime(dtBuf, sizeof(dtBuf), L"%Y-%m-%d %H:%M:%S", &lNow); 68 | 69 | if (LogSourceLocation > 0) { 70 | swprintf(dtBuf, sizeof(dtBuf), L"%s: File=%S, Function=%S, Line=%d: %s", dtBuf, FFILE, FFUNCTION, FLINE, msg); 71 | } 72 | else { 73 | swprintf(dtBuf, sizeof(dtBuf), L"%s: %s", dtBuf, msg); 74 | } 75 | logMessageToFile(dtBuf); 76 | logMessageToConsole(dtBuf); 77 | } 78 | //================================================================================================= 79 | void CacheLogger::logMessage(wchar_t* msg) 80 | { 81 | LogMessage(msg); 82 | } 83 | //================================================================================================= 84 | void CacheLogger::consoleMessage(wchar_t * msg) 85 | { 86 | wprintf (L"%s\n", msg); 87 | } 88 | //================================================================================================= 89 | wchar_t* CacheLogger::getLastErrorCode() 90 | { 91 | wchar_t buf[128] = L"0x"; 92 | _itow(GetLastError(), buf + wcslen(buf), 16); 93 | return _wcsdup(buf); 94 | } 95 | //================================================================================================= 96 | wchar_t* CacheLogger::getLastErrorMsg() 97 | { 98 | wchar_t buf[1024]; 99 | FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), 0, buf, 1024, NULL); 100 | swprintf(buf, sizeof(buf), L"%s", buf); 101 | return _wcsdup(buf); 102 | } 103 | //================================================================================================= 104 | void CacheLogger::logLastError() 105 | { 106 | wchar_t buf[1024]; 107 | swprintf(buf, sizeof(buf), L"LastError Code=%s, Msg=%s", getLastErrorCode(), getLastErrorMsg()); 108 | LogMessage(buf); 109 | } 110 | //================================================================================================= 111 | void CacheLogger::logError(wchar_t * msg) 112 | { 113 | logLastError(); 114 | logMessage(msg); 115 | } -------------------------------------------------------------------------------- /CacheCryptoAPI/CacheCryptoAPI.h: -------------------------------------------------------------------------------- 1 | // CacheCryptoAPI.h 2 | 3 | #pragma once 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #include "callin.h" 14 | #include "cdzf.h" 15 | #include "CacheLogger.h" 16 | 17 | //using namespace System; 18 | 19 | #define MAX_HASH_SIZE 4096 20 | #define MAX_SIGN_SIZE 4096 21 | #define MAX_DATA_SIZE 32768 22 | 23 | struct CryptoRecord 24 | { 25 | char * data; 26 | unsigned int len; 27 | CryptoRecord() {data=NULL; len=0;}; 28 | }; 29 | 30 | class CacheCommon : public CacheLogger 31 | { 32 | // Class variables 33 | HCRYPTPROV hProv; // descriptor of CSP, that is created by CryptAcquireContext 34 | HCRYPTKEY hKey; // descriptor of key, created by CryptGetUserKey 35 | HCRYPTHASH hHash; // descriptor of hash, created in hashData function 36 | 37 | DWORD globalProviderID; // id of CSP 38 | DWORD globalHashAlgID; // id of hash algorithm, can be used instead of globalSignAlgID 39 | DWORD globalSignAlgID; // id of sign algorithm 40 | BOOL globalMKS; // flag of machine keyset usage 41 | BOOL globalSilentFlag; // flag of providing operations in silent mode 42 | 43 | wchar_t* globalPIN; // pincode to reach keys 44 | wchar_t* globalContainerName; // name of CSP keys container 45 | wchar_t* globalProviderName; // name of CSP 46 | 47 | char* localString; // string, basement for Hash string creation, last entered value 48 | CryptoRecord localHash; // hash value, last created with hashData or signNewHash methods 49 | CryptoRecord localSign; // signature value, last created with signNewHash or signCurrentHash methods 50 | CryptoRecord localKey; // key value, generated with exportUserKey method 51 | 52 | // Methods 53 | public: 54 | CacheCommon(); 55 | ~CacheCommon(); 56 | 57 | BOOL getGlobalMKS() {return globalMKS;}; // get value of globalMKS (machine key set flag), inline method 58 | void setGlobalMKS(BOOL newMKS) {globalMKS=newMKS;}; // set value of globalMKS, inline method 59 | 60 | wchar_t* getGlobalProviderName() {return globalProviderName;}; // get value of globalProviderName, inline method 61 | void setGlobalProviderName(wchar_t * newGlobalProviderName) {globalProviderName = _wcsdup(newGlobalProviderName);}; // set value of globalProviderName, inline method 62 | 63 | wchar_t* getGlobalContainerName() {return globalContainerName;}; // get value of globalContainerName, inline method 64 | void setGlobalContainerName(wchar_t * newGlobalContainerName) {globalContainerName = _wcsdup(newGlobalContainerName);}; // set value of globalContainerName, inline method 65 | 66 | wchar_t* getGlobalPIN() {return globalPIN;}; // get value of globalPIN, inline method 67 | void setGlobalPIN(wchar_t * newGlobalPIN) {globalPIN = _wcsdup(newGlobalPIN);}; // set value of globalPIN, inline method 68 | 69 | DWORD getGlobalProviderID() {return globalProviderID;}; // get value of globalPIN, inline method 70 | void setGlobalProviderID(DWORD newGlobalProviderID) {globalProviderID = newGlobalProviderID;}; // set value of globalPIN, inline method 71 | 72 | DWORD getGlobalAlgID() {return globalHashAlgID;}; // get value of globalHashAlgID, inline method 73 | void setGlobalAlgID(DWORD newGlobalHashAlgID) {globalHashAlgID = newGlobalHashAlgID;}; // set value of globalHashAlgID, inline method 74 | 75 | char * getLocalString() {return localString;}; // get value of localString 76 | void updateLocalString(char * newString); // update value of localString 77 | 78 | char * getLocalHashString() {return localHash.data;}; // get value of localHash.data, inline method 79 | void updateLocalHashString(char * newHashString, unsigned int newSize); // update localHash 80 | unsigned int getHashLength() {return localHash.len;}; // get value of localHash.len, inline method 81 | void setHashLength(unsigned int newHashLength) {localHash.len = newHashLength;}; // set value of localHash.len, inline method 82 | CryptoRecord * getLocalHash() {return &localHash;}; // get pointer of localHash structure, inline method 83 | 84 | char * getLocalSignature() {return localSign.data;}; // get value of localSign.data, inline method 85 | void updateLocalSignature(char * newLocalSignature, unsigned int newSize); // update localSign 86 | unsigned int getSignatureLength() {return localSign.len;}; // get value of localSign.len, inline method 87 | void setSignatureLength(unsigned int newSignatureLength) {localSign.len = newSignatureLength;}; // set value of localSign.len, inline method 88 | CryptoRecord * getLocalSign() {return &localSign;}; // get pointer of localSign structure, inline method 89 | 90 | CryptoRecord * getLocalKey() {return &localKey;}; // get pointer of localKey structure, inline method 91 | void updateLocalKey(char * newLocalKey, unsigned int newSize); // update localKey 92 | 93 | int Init(DWORD provTypeId, DWORD algId, wchar_t *containerName, wchar_t *pin, wchar_t *providerName); // initialize fields with values from function parameters and calls AcquireContext 94 | HCRYPTPROV AcquireContext(); // acquires context 95 | void ReleaseContext(); // releases context 96 | void printProviders(); // output available providers to file or console 97 | void printProviderParams(); // output parameters of provider to file or console 98 | int hashData(char * hashString); // hash data 99 | int hashFile(char * fileName); // hash file content 100 | int destroyHash(); // empty hHash pointer 101 | int initHashValue(CryptoRecord * hashVal); // create new hash object and initialize it with hashVal value 102 | int getHashValue(CryptoRecord * hashVal = NULL); // get hash value into hashVal, if hashVal is NULL, just log it 103 | int signNewHash(char * hashVal, CryptoRecord * signVal); // create new hash and sign it, signVal returns signature 104 | int signCurrentHash(CryptoRecord * signVal); // sign currently existing hash, returns signature in signVal 105 | int verifyHash(CryptoRecord * hashVal, CryptoRecord * signVal, int *result); // verify if the signVal is correct for provided hashVal 106 | int verifyHashByKey(CryptoRecord * hashVal, CryptoRecord * signVal, CryptoRecord * pubKey, int * result); // verify if the signVal is correct for provided hashVal with additional public key 107 | int verifySignature(char * hashString, CryptoRecord * signVal, int *result); // verify if the signVal is correct for provided string. First create hash for string hashVal, then verify signature 108 | int exportUserKey(CryptoRecord * keyVal); 109 | 110 | // Utils 111 | static void ByteToStr(DWORD cb, void* pv, LPSTR sz); 112 | static void ByteToZARRAY(int len, unsigned char *buf, ZARRAYP bytestr); 113 | static void ReverseByteToZARRAY(int len, unsigned char *buf, ZARRAYP bytestr); 114 | }; 115 | -------------------------------------------------------------------------------- /CacheCryptoAPI/CacheCryptoAPI.vcxproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Debug 10 | x64 11 | 12 | 13 | Release 14 | Win32 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | {2977F54B-E87B-48DA-BA5B-7584942AD76F} 23 | v4.0 24 | ManagedCProj 25 | CacheCryptoAPI 26 | 27 | 28 | 29 | StaticLibrary 30 | true 31 | true 32 | Unicode 33 | 34 | 35 | StaticLibrary 36 | true 37 | true 38 | Unicode 39 | 40 | 41 | StaticLibrary 42 | false 43 | true 44 | Unicode 45 | 46 | 47 | StaticLibrary 48 | false 49 | true 50 | Unicode 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | true 70 | .lib 71 | C:\InterSystems\Ensemble\dev\cpp\include;$(IncludePath) 72 | $(ProjectDir)$(Platform)\$(Configuration)\ 73 | 74 | 75 | true 76 | .lib 77 | C:\InterSystems\Ensemble\dev\cpp\include;$(IncludePath) 78 | $(SolutionDir)$(Configuration)\ 79 | 80 | 81 | false 82 | C:\InterSystems\Ensemble\dev\cpp\include;$(IncludePath) 83 | $(ProjectDir)$(Platform)\$(Configuration)\ 84 | 85 | 86 | false 87 | C:\InterSystems\Ensemble\dev\cpp\include;$(IncludePath) 88 | $(ProjectDir)$(Configuration)\ 89 | 90 | 91 | 92 | Level2 93 | Disabled 94 | Use 95 | 96 | 97 | true 98 | 99 | 100 | 101 | 102 | MachineX64 103 | 104 | 105 | 106 | 107 | Level3 108 | Disabled 109 | Use 110 | 111 | 112 | true 113 | 114 | 115 | 116 | 117 | 118 | 119 | Level2 120 | WIN32;NDEBUG;%(PreprocessorDefinitions) 121 | Use 122 | Full 123 | 124 | 125 | false 126 | 127 | 128 | 129 | 130 | MachineX64 131 | 132 | 133 | 134 | 135 | Level3 136 | WIN32;NDEBUG;%(PreprocessorDefinitions) 137 | Use 138 | Full 139 | 140 | 141 | true 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | Create 163 | Create 164 | Create 165 | Create 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | -------------------------------------------------------------------------------- /CacheCryptoConsole/CacheCryptoConsole.vcxproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Debug 10 | x64 11 | 12 | 13 | Release 14 | Win32 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | {4616D38F-98F0-4D47-9698-8A01F50E11BE} 23 | v4.0 24 | ManagedCProj 25 | CacheCryptoConsole 26 | 27 | 28 | 29 | Application 30 | true 31 | true 32 | Unicode 33 | 34 | 35 | Application 36 | true 37 | true 38 | Unicode 39 | 40 | 41 | Application 42 | false 43 | true 44 | Unicode 45 | 46 | 47 | Application 48 | false 49 | true 50 | Unicode 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | true 70 | $(SolutionDir)\CacheCryptoAPI\$(Configuration)\;$(LibraryPath) 71 | C:\InterSystems\Ensemble\dev\cpp\include;$(IncludePath) 72 | $(ProjectDir)$(Platform)\$(Configuration)\ 73 | 74 | 75 | true 76 | $(SolutionDir)CacheCryptoAPI\$(Platform)\$(Configuration);$(LibraryPath) 77 | C:\InterSystems\Ensemble\dev\cpp\include;$(IncludePath) 78 | $(ProjectDir)$(Platform)\$(Configuration)\ 79 | 80 | 81 | false 82 | C:\InterSystems\Ensemble\dev\cpp\include;$(IncludePath) 83 | $(SolutionDir)CacheCryptoAPI\$(Configuration);$(LibraryPath) 84 | $(ProjectDir)$(Configuration)\ 85 | 86 | 87 | false 88 | $(SolutionDir)CacheCryptoAPI\$(Platform)\$(Configuration);$(LibraryPath) 89 | C:\InterSystems\Ensemble\dev\cpp\include;$(IncludePath) 90 | $(ProjectDir)$(Platform)\$(Configuration)\ 91 | 92 | 93 | 94 | Level3 95 | Disabled 96 | WIN32;_DEBUG;%(PreprocessorDefinitions) 97 | Use 98 | 99 | 100 | true 101 | CacheCryptoAPI.lib;%(AdditionalDependencies) 102 | 103 | 104 | 105 | 106 | Level3 107 | Disabled 108 | WIN32;_DEBUG;%(PreprocessorDefinitions) 109 | Use 110 | 111 | 112 | true 113 | CacheCryptoAPI.lib;%(AdditionalDependencies) 114 | 115 | 116 | 117 | 118 | Level3 119 | WIN32;NDEBUG;%(PreprocessorDefinitions) 120 | Use 121 | Full 122 | 123 | 124 | true 125 | CacheCryptoAPI.lib;%(AdditionalDependencies) 126 | 127 | 128 | 129 | 130 | Level3 131 | WIN32;NDEBUG;%(PreprocessorDefinitions) 132 | Use 133 | Full 134 | 135 | 136 | true 137 | CacheCryptoAPI.lib;%(AdditionalDependencies) 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | Create 161 | Create 162 | Create 163 | Create 164 | 165 | 166 | 167 | 168 | 169 | -------------------------------------------------------------------------------- /ISCAPI/ISCAPI.cpp: -------------------------------------------------------------------------------- 1 | // This is the main DLL file. 2 | 3 | #include "stdafx.h" 4 | #include "ISCAPI.h" 5 | 6 | #define ZF_DLL 7 | #include "cdzf.h" 8 | #include "..\CacheCryptoAPI\CacheCryptoAPI.h" 9 | 10 | CacheCommon cacheCommon; 11 | //================================================================================================= 12 | // Print cryptographic providers currently available in OS 13 | int printProviders() 14 | { 15 | cacheCommon.printProviders(); 16 | return 0; 17 | } 18 | //================================================================================================= 19 | // Initialization of cryptoprovider 20 | // provTypeId - ID of CSP 21 | // algId - algorithm ID 22 | // containerName - name of keys container, available for your CSP 23 | // pin - pin code for selected key container 24 | // providerName - name of selected CSP 25 | int Init(DWORD provTypeId, DWORD algId, wchar_t *containerName, wchar_t *pin, wchar_t *providerName) 26 | { 27 | cacheCommon.Init(provTypeId, algId, containerName, pin, providerName); // set parameters and acquire context 28 | return 0; 29 | } 30 | //================================================================================================= 31 | // Acquire context function, should be called before other operations with CSP 32 | int AcquireContext() 33 | { 34 | cacheCommon.AcquireContext(); 35 | return 0; 36 | } 37 | //================================================================================================= 38 | // Release acquired earlier context. Should pair all AcquireContext functions, otherwise slow down operational performance on server 39 | int ReleaseContext() 40 | { 41 | cacheCommon.ReleaseContext(); 42 | return 0; 43 | } 44 | //================================================================================================= 45 | // Hash data string provided in parameter "dataToHash" 46 | // dataToHash - string to hash and its size 47 | int HashData(ZARRAYP dataToHash) 48 | { 49 | // transition to avoid bad strings from COS CALLOUT 50 | char cData[MAX_DATA_SIZE]; 51 | sprintf(cData, "%s", dataToHash->data); 52 | cData[dataToHash->len]=NULL; 53 | cacheCommon.hashData(cData); 54 | 55 | return 0; 56 | } 57 | //================================================================================================= 58 | // Hash file, file name is provided in parameter "fileName" 59 | int HashFile(ZARRAYP fileName) 60 | { 61 | // transition to avoid bad strings from COS CALLOUT 62 | char cFileName[1024]; 63 | sprintf(cFileName, "%s", fileName->data); 64 | cFileName[fileName->len]=NULL; 65 | cacheCommon.hashFile(cFileName); 66 | 67 | return 0; 68 | } 69 | //================================================================================================= 70 | // Return value of previously created hash 71 | // hashVal - returned hash string and its size 72 | int GetHashValue(ZARRAYP hashVal) 73 | { 74 | CryptoRecord tempHash; 75 | cacheCommon.getHashValue(&tempHash); 76 | cacheCommon.ByteToZARRAY(tempHash.len, (BYTE*)tempHash.data, hashVal); 77 | hashVal->data[hashVal->len]=NULL; 78 | 79 | wchar_t dtBuf[1024]; 80 | swprintf(dtBuf, L"Hash at Class side: %S, length: %i", cacheCommon.getLocalHashString(), cacheCommon.getHashLength()); 81 | cacheCommon.logMessage(dtBuf); 82 | return 0; 83 | } 84 | //================================================================================================= 85 | // Sign currently available hash in system. Hash could be previously created with HashData function 86 | // signVal - retuning value of signature string and its size 87 | int SignCurrentHash(ZARRAYP signVal) 88 | { 89 | CryptoRecord tempSign; 90 | cacheCommon.signCurrentHash(&tempSign); 91 | 92 | cacheCommon.ByteToZARRAY(tempSign.len, (BYTE*)tempSign.data, signVal); 93 | signVal->data[signVal->len]=NULL; 94 | 95 | wchar_t dtBuf[1024]; 96 | swprintf(dtBuf, L"Signature at Class side: %S, length: %i", cacheCommon.getLocalSignature(), cacheCommon.getSignatureLength()); 97 | cacheCommon.logMessage(dtBuf); 98 | 99 | return 0; 100 | } 101 | //================================================================================================= 102 | // Create new hash string and sign it 103 | // hashVal - string to build hash and its size 104 | // signVal - retuning value of signature string and its size 105 | int SignNewHash(ZARRAYP hashVal, ZARRAYP signVal) 106 | { 107 | cacheCommon.signNewHash((char*)hashVal->data, cacheCommon.getLocalSign()); 108 | cacheCommon.ByteToZARRAY(cacheCommon.getSignatureLength(), (BYTE*)cacheCommon.getLocalSignature(), signVal); 109 | return 0; 110 | } 111 | //================================================================================================= 112 | // Verify signature by hash 113 | // hashVal - hashed string 114 | // signVal - signed hash string 115 | // result - operation result: 1-success, 0-failure 116 | int VerifyHash(ZARRAYP hashVal, ZARRAYP signVal, int *result) 117 | { 118 | // copy hashVal and signVal to local structures 119 | cacheCommon.updateLocalHashString((char*)hashVal->data, hashVal->len); 120 | cacheCommon.updateLocalSignature((char*)signVal->data, signVal->len); 121 | 122 | // use local copies to verify signature 123 | cacheCommon.verifyHash(cacheCommon.getLocalHash(), cacheCommon.getLocalSign(), result); 124 | return 0; 125 | } 126 | //================================================================================================= 127 | // Verify signature by initial string 128 | // dataToHash - initial string 129 | // signVal - signed hash string 130 | // result - operation result: 1-success, 0-failure 131 | int VerifySignature(ZARRAYP dataToHash, ZARRAYP signVal, int *result) 132 | { 133 | // transition to avoid bad strings from COS CALLOUT 134 | char cData[MAX_DATA_SIZE]; 135 | sprintf(cData, "%s", dataToHash->data); 136 | cData[dataToHash->len]=NULL; 137 | cacheCommon.updateLocalString(cData); 138 | 139 | cacheCommon.updateLocalSignature((char*)signVal->data, signVal->len); 140 | 141 | // use local copies to verify signature 142 | cacheCommon.verifySignature(cacheCommon.getLocalString(), cacheCommon.getLocalSign(), result); 143 | return 0; 144 | } 145 | //================================================================================================= 146 | // Verify signature by hash and key 147 | // hashVal - hashed string 148 | // signVal - signed hash string 149 | // keyVal - key string, used to sign hash 150 | // result - operation result: 1-success, 0-failure 151 | int VerifyHashByKey(ZARRAYP hashVal, ZARRAYP signVal, ZARRAYP keyVal, int *result) 152 | { 153 | // copy hashVal and signVal to local structures 154 | cacheCommon.updateLocalHashString((char*)hashVal->data, hashVal->len); 155 | cacheCommon.updateLocalSignature((char*)signVal->data, signVal->len); 156 | cacheCommon.updateLocalKey((char*)keyVal->data, keyVal->len); 157 | 158 | // use local copies to verify signature 159 | cacheCommon.verifyHashByKey(cacheCommon.getLocalHash(), cacheCommon.getLocalSign(), cacheCommon.getLocalKey(), result); 160 | return 0; 161 | } 162 | //================================================================================================= 163 | // Build key string ready to transfer 164 | // keyVal - resulting key string and its size, can be later transfered to recieving side 165 | int ExportKey(ZARRAYP keyVal) 166 | { 167 | cacheCommon.exportUserKey(cacheCommon.getLocalKey()); 168 | cacheCommon.ByteToZARRAY(cacheCommon.getLocalKey()->len, (BYTE*)cacheCommon.getLocalKey()->data, keyVal); 169 | return 0; 170 | } 171 | //================================================================================================= 172 | // Release resourses, hash and context 173 | int ReleaseAll() 174 | { 175 | cacheCommon.destroyHash(); 176 | ReleaseContext(); 177 | return 0; 178 | } 179 | //================================================================================================= 180 | // Initialize Logger fnctionality 181 | // logFileName - name of file 182 | // logLevel - 0-none, 1-only errors, 2- all events 183 | // logTargets - 1-file, 2-console, 3-both 184 | int InitLogger(wchar_t* logFileName, int logLevel, int logTargets) 185 | { 186 | cacheCommon.setLogLevel(logLevel); 187 | cacheCommon.setLogFileName(logFileName); 188 | cacheCommon.setLogTargets(logTargets); 189 | cacheCommon.setLogSourceLocation(0); 190 | return 0; 191 | } 192 | //================================================================================================= 193 | // Output one log message 194 | // msg - text of message 195 | int LogMessageCOS(wchar_t* msg) 196 | { 197 | cacheCommon.logMessage(msg); 198 | return 0; 199 | } 200 | //================================================================================================= 201 | ZFBEGIN 202 | ZFENTRY("LogMessage", "w", LogMessageCOS) 203 | ZFENTRY("Init", "iiwww", Init) 204 | ZFENTRY("InitLogger", "wii", InitLogger) 205 | ZFENTRY("AContext", "", AcquireContext) 206 | ZFENTRY("RContext", "", ReleaseContext) 207 | ZFENTRY("HashData", "b", HashData) 208 | ZFENTRY("HashFile", "b", HashFile) 209 | ZFENTRY("GetHashValue", "B", GetHashValue) 210 | ZFENTRY("SignCurrentHash", "B", SignCurrentHash) 211 | ZFENTRY("SignNewHash", "bB", SignNewHash) 212 | ZFENTRY("VerifyHash", "bbP", VerifyHash) 213 | ZFENTRY("VerifyHashByKey", "bbbP", VerifyHashByKey) 214 | ZFENTRY("VerifySignature", "bbP", VerifySignature) 215 | ZFENTRY("ExportUserKey", "B", ExportKey) 216 | ZFENTRY("PrintProviders", "", printProviders) 217 | ZFENTRY("ReleaseAll", "", ReleaseAll) 218 | ZFEND 219 | -------------------------------------------------------------------------------- /ISCAPI/ISCAPI.vcxproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Debug 10 | x64 11 | 12 | 13 | Release 14 | Win32 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | {78B87F2F-299B-4C6C-B76B-7070F34C02E0} 23 | v4.0 24 | ManagedCProj 25 | ISCAPI 26 | 27 | 28 | 29 | DynamicLibrary 30 | true 31 | true 32 | Unicode 33 | false 34 | 35 | 36 | DynamicLibrary 37 | true 38 | true 39 | Unicode 40 | false 41 | 42 | 43 | DynamicLibrary 44 | false 45 | true 46 | Unicode 47 | 48 | 49 | DynamicLibrary 50 | false 51 | true 52 | Unicode 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | true 72 | C:\InterSystems\Ensemble\dev\cpp\include;$(IncludePath) 73 | $(VCInstallDir)atlmfc\lib\amd64;$(VCInstallDir)lib\amd64 74 | C:\Users\Artem\Documents\Visual Studio 2010\Projects\CacheCryptoAPI\CacheCryptoAPI\x64\Debug;$(LibraryPath) 75 | $(ProjectDir)$(Platform)\$(Configuration)\ 76 | 77 | 78 | true 79 | C:\InterSystems\Ensemble\dev\cpp\include;$(IncludePath) 80 | $(VCInstallDir)atlmfc\lib\amd64;$(VCInstallDir)lib\amd64 81 | $(SolutionDir)CacheCryptoAPI\$(Platform)\$(Configuration);$(LibraryPath) 82 | $(ProjectDir)$(Platform)\$(Configuration)\ 83 | 84 | 85 | false 86 | C:\InterSystems\Ensemble\dev\cpp\include;$(IncludePath) 87 | $(SolutionDir)CacheCryptoAPI\$(Configuration);$(LibraryPath) 88 | $(ProjectDir)$(Configuration)\ 89 | 90 | 91 | false 92 | $(SolutionDir)CacheCryptoAPI\$(Platform)\$(Configuration);$(LibraryPath) 93 | C:\InterSystems\Ensemble\dev\cpp\include;$(IncludePath) 94 | $(ProjectDir)$(Platform)\$(Configuration)\ 95 | 96 | 97 | 98 | Level3 99 | Disabled 100 | DEBUG;%(PreprocessorDefinitions) 101 | Use 102 | 103 | 104 | true 105 | CacheCryptoAPI.lib;%(AdditionalDependencies) 106 | 107 | 108 | MachineX64 109 | 110 | 111 | 112 | 113 | Level3 114 | Disabled 115 | DEBUG;%(PreprocessorDefinitions) 116 | Use 117 | 118 | 119 | true 120 | CacheCryptoAPI.lib;%(AdditionalDependencies) 121 | 122 | 123 | 124 | 125 | 126 | 127 | Level3 128 | WIN32;NDEBUG;%(PreprocessorDefinitions) 129 | Use 130 | Full 131 | 132 | 133 | true 134 | CacheCryptoAPI.lib;%(AdditionalDependencies) 135 | 136 | 137 | 138 | 139 | Level3 140 | WIN32;NDEBUG;%(PreprocessorDefinitions) 141 | Use 142 | Full 143 | 144 | 145 | true 146 | CacheCryptoAPI.lib;%(AdditionalDependencies) 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | Create 164 | Create 165 | Create 166 | Create 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | -------------------------------------------------------------------------------- /iscapi.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Функции для работы с крипто-провайдерами через MS CAPI 6 | %RegisteredObject 7 | 63095,54910.929709 8 | 62647,62739.879273 9 | 10 | 11 | 12 | Загрузка DLL 13 | dllPath - полный путь к библиотеке 14 | 1 15 | dllPath:%String 16 | %Status 17 | 37 | 38 | 39 | 40 | 41 | Выгрузка DLL 42 | 1 43 | 45 | 46 | 47 | 48 | 49 | Инициализация крипто-провайдера. 50 | provType - тип провайдера (VipNet=2, CryptoPro=75) 51 | algId - используемый алгоритм (32798) 52 | containerName - полное имя контейнера с ключами 53 | pin - пароль к контейнеру (если не указан, CSP будет запршивать его в интерактивном режиме, что не всегда возможно) 54 | providerName - имя крипто-провайдера 55 | 1 56 | provType=75,algId=32798,containerName:%String,pin:%String="111111",providerName:%String="" 57 | %Status 58 | 73 | 74 | 75 | 76 | 77 | Инициализация протоколирования. 78 | logFileName - имя файла протокола. Должно быть право на запись. 79 | logLevel - уровень протоколирования 80 | 0 - ничего 81 | 1 - только ошибки 82 | 2 - все сообщения 83 | logTargets - устройства, в которые нужно писать протокол 84 | 0 - не писать никуда 85 | 1 - писать в файл 86 | 2 - выводить на консоль 87 | 3 - файл и консоль 88 | 1 89 | logFileName:%String="c:\iscapi.log",logLevel:%Integer=2,logTargets:%Integer=3 90 | %Status 91 | 106 | 107 | 108 | 109 | 110 | Хеширование порции данных. 111 | Можно вызывать в цикле для хеширования потока по чанкам, каждая порция данных будет прибавляться к хешу. 112 | 1 113 | dataPortion:%String 114 | %Status 115 | 125 | 126 | 127 | 128 | 129 | Хеширование файла. 130 | 1 131 | fileName:%String 132 | %Status 133 | 143 | 144 | 145 | 146 | 147 | Возвращает значение хеша. 148 | После вызова хеш сохраняется 149 | 1 150 | %String 151 | 165 | 166 | 167 | 168 | 1 169 | %String 170 | 180 | 181 | 182 | 183 | 184 | Экспорт открытого ключа. 185 | Подпись хеша. 186 | 1 187 | dataPortion:%String 188 | %String 189 | 199 | 200 | 201 | 202 | 203 | Подпись текущего объекта хеша. 204 | 1 205 | %String 206 | 218 | 219 | 220 | 221 | 222 | Проверка подписи хэша. 223 | 1 224 | hash:%String,sign:%String 225 | %Boolean 226 | 236 | 237 | 238 | 239 | 1 240 | hash:%String,sign:%String,pubKey:%String 241 | %Boolean 242 | 252 | 253 | 254 | 255 | 256 | Проверка подписи хэша по открытому ключу. 257 | Проверка подписи данных 258 | 1 259 | dataPortion:%String,sign:%String 260 | %Boolean 261 | 271 | 272 | 273 | 274 | 275 | Освобождение ресурсов и выгрузка DLL 276 | 1 277 | %Status 278 | 289 | 290 | 291 | 292 | 293 | Преобразование бинарной строки в HEX 294 | TODO: rewrite 295 | 1 296 | bString:%String 297 | %String 298 | 307 | 308 | 309 | 310 | 1 311 | value:%String 312 | %String 313 | 322 | 323 | 324 | 325 | 326 | Выгрузка DLL 327 | 1 328 | %Status 329 | 340 | 341 | 342 | 343 | 344 | Тестовый прогон КриптоПро 345 | 1 346 | 388 | 389 | 390 | 391 | 392 | 393 | -------------------------------------------------------------------------------- /CacheCryptoConsole/CacheCryptoConsole.cpp: -------------------------------------------------------------------------------- 1 | // CacheCryptoConsole.cpp : Defines the entry point for the console application. 2 | //Crypto-Pro GOST R 34.10-2001 Cryptographic Service Provider 3 | // s cl = ##class(iscapi.Signer).%New() 4 | // s st = cl.LoadDLL("c:\ARTEM\ISCAPI1.dll") 5 | // s st = cl.InitCSP() 6 | 7 | #include "stdafx.h" 8 | #include "conio.h" 9 | #include "string.h" 10 | #include 11 | #include 12 | #include 13 | 14 | #include "..\CacheCryptoAPI\CacheCryptoAPI.h" 15 | 16 | 17 | using namespace std; 18 | 19 | CacheCommon * cacheCommon; 20 | CryptoRecord signature; 21 | CryptoRecord key; 22 | char tempHash[MAX_HASH_SIZE]; 23 | wchar_t tBuf[1024]; 24 | 25 | //================================================================================================= 26 | // function set console window parameters 27 | void setWindow() 28 | { 29 | // set window size 30 | HANDLE out_handle = GetStdHandle(STD_OUTPUT_HANDLE); 31 | COORD crd = {1000, 800}; 32 | SMALL_RECT src = {0, 0, crd.X-1, crd.Y-1}; 33 | SetConsoleWindowInfo (out_handle, true, &src); 34 | SetConsoleScreenBufferSize (out_handle, crd); 35 | HWND hwnd; 36 | 37 | wchar_t Title[1024]; 38 | GetConsoleTitle(Title, 1024); 39 | hwnd=FindWindow(NULL, Title); 40 | MoveWindow(hwnd,20,20,1000,800,TRUE); 41 | } 42 | 43 | //================================================================================================= 44 | // function shows available commands 45 | void show_usage() 46 | { 47 | // show usage 48 | printf("Usage:\n"); 49 | 50 | printf(" help()\n"); 51 | printf("\t ... show available commands\n"); 52 | 53 | printf(" showProviders()\n"); 54 | printf("\t ... show providers available in system\n"); 55 | 56 | printf(" showProvParams()\n"); 57 | printf("\t ... show provider parameters available in system\n"); 58 | 59 | printf(" print()\n"); 60 | printf("\t ... show current set values\n"); 61 | 62 | printf(" arContext(int ProviderType)\n"); 63 | printf("\t ... acquire and release context for provider\n"); 64 | 65 | printf(" aContext(int ProviderType)\n"); 66 | printf("\t ... acquire context for provider\n"); 67 | 68 | printf(" rContext(int ProviderType)\n"); 69 | printf("\t ... release context for provider\n"); 70 | 71 | printf(" hashData(string textToHash)\n"); 72 | printf("\t ... hash data string\n"); 73 | 74 | printf(" hashFile(string fileName)\n"); 75 | printf("\t ... hash file\n"); 76 | 77 | printf(" getHashValue\n"); 78 | printf("\t ... get hash Value\n"); 79 | 80 | printf(" signCurrentHash()\n"); 81 | printf("\t ... sign existing hash \n"); 82 | 83 | printf(" signNewHash(string textToHash)\n"); 84 | printf("\t ... create new hash and sign it\n"); 85 | 86 | printf(" destroyHash()\n"); 87 | printf("\t ... clear hash object\n"); 88 | 89 | printf(" verifyHash()\n"); 90 | printf("\t ... verify signature by hash\n"); 91 | 92 | printf(" verifyHashByKey()\n"); 93 | printf("\t ... verify signature by hash and key\n"); 94 | 95 | printf(" verifySignature(string textToHash)\n"); 96 | printf("\t ... verify signatue by initial string\n"); 97 | 98 | printf(" exportKey()\n"); 99 | printf("\t ... export key \n"); 100 | 101 | printf(" provID(int Provider ID)\n"); 102 | printf("\t ... set provider ID \n"); 103 | 104 | printf(" algID(int Algorithm ID)\n"); 105 | printf("\t ... set algorithm ID \n"); 106 | 107 | printf(" contName(string Container Name ID)\n"); 108 | printf("\t ... set container name ID \n"); 109 | 110 | printf(" provName(string Provider Name ID)\n"); 111 | printf("\t ... set provider name ID \n"); 112 | 113 | printf(" contPIN(string PIN)\n"); 114 | printf("\t ... set new PIN \n"); 115 | 116 | } 117 | //================================================================================================= 118 | // function clears vector, free all alocated memory 119 | int clear_vector(std::vector &myVec) 120 | { 121 | int i; 122 | for(i=0; i<(int)myVec.size(); ++i) 123 | delete[] myVec[i]; 124 | myVec.clear(); 125 | return i; 126 | } 127 | //================================================================================================= 128 | // function parses string on vector of parameters 129 | int parse_params(wchar_t * commandStr, std::vector ¶ms) 130 | { 131 | int ret = 0; 132 | if (!commandStr) 133 | return ret; 134 | 135 | clear_vector(params); 136 | 137 | bool openedQuote = false; 138 | int startPos=0; 139 | for (int i=0; i<=wcslen(commandStr); ++i) 140 | { 141 | if (commandStr[i]=='"') 142 | { 143 | openedQuote=!openedQuote; 144 | continue; 145 | } 146 | 147 | if ((commandStr[i]==0x20) || (commandStr[i]==NULL)) 148 | { 149 | if (openedQuote) continue; 150 | if ( (i-startPos)>=1) //avoids two following spaces 151 | { 152 | wchar_t * param = new wchar_t[i-startPos+1]; 153 | wcsncpy(param, commandStr+startPos, i-startPos); 154 | param[i-startPos]=NULL; 155 | if (param[0]=='"') // trim string from quotes 156 | { 157 | wchar_t * newParam = new wchar_t[wcslen(param)-2+1]; 158 | wcsncpy(newParam, param+1, wcslen(param)-2); 159 | newParam[wcslen(param)-2]=NULL; 160 | delete[] param; 161 | param=newParam; 162 | } 163 | params.push_back(param); 164 | } 165 | startPos=i+1; 166 | } 167 | } 168 | return params.size(); 169 | } 170 | //================================================================================================= 171 | //output list of available providers and their types 172 | void showProviders() { 173 | cacheCommon->printProviders(); 174 | } 175 | //================================================================================================= 176 | // aquire context for internal calls 177 | HCRYPTPROV simpleAC(DWORD provType) 178 | { 179 | cacheCommon->setGlobalProviderID(provType); 180 | return cacheCommon->AcquireContext(); 181 | } 182 | //================================================================================================= 183 | // release context for internal calls 184 | void simpleRC(HCRYPTPROV hCryptProv) 185 | { 186 | cacheCommon->ReleaseContext(); 187 | } 188 | //================================================================================================= 189 | // show parameters of selected provider 190 | void showProviderParams() { 191 | cacheCommon->printProviderParams(); 192 | } 193 | //================================================================================================= 194 | //test acquiring and releasing context 195 | void acquireReleaseContext(DWORD provType) { 196 | 197 | simpleAC(provType); 198 | simpleRC(provType); 199 | } 200 | //================================================================================================= 201 | //aqcuire context 202 | void acquireContext(DWORD provType) { 203 | simpleAC(provType); 204 | } 205 | //================================================================================================= 206 | //release context 207 | void releaseContext(DWORD provType) { 208 | simpleRC(provType); 209 | } 210 | //================================================================================================= 211 | // create a hash based on sData string 212 | void HashData(wchar_t * sData) 213 | { 214 | if (!sData) 215 | cacheCommon->logMessage(L"No data to hash"); 216 | 217 | char cData[MAX_DATA_SIZE]; 218 | sprintf(cData, "%S", sData); 219 | cacheCommon->hashData(cData); 220 | } 221 | //================================================================================================= 222 | // create a hash based on sData string 223 | void HashFile(wchar_t * sFileName) 224 | { 225 | if (!sFileName) 226 | cacheCommon->logMessage(L"No file specified"); 227 | 228 | char cFileName[1024]; 229 | sprintf(cFileName, "%S", sFileName); 230 | cacheCommon->hashFile(cFileName); 231 | } 232 | //================================================================================================= 233 | // get and log hash string 234 | void GetHashValue() 235 | { 236 | wchar_t * hashVal = NULL; 237 | cacheCommon->getHashValue(); 238 | 239 | return; 240 | } 241 | //================================================================================================= 242 | // create a hash and sign it 243 | // sHash - string, used to create hash string 244 | void SignNewHash(wchar_t * sHash) 245 | { 246 | // create ZARRAYP structure from wchar_t input string 247 | if (!sHash) 248 | cacheCommon->logMessage(L"No data to hash"); 249 | 250 | char cHash[MAX_DATA_SIZE]; 251 | sprintf(cHash, "%S", sHash); 252 | 253 | 254 | CacheCommon * tmp = cacheCommon; 255 | cacheCommon->signNewHash(cHash, &signature); 256 | // after copying signature, pointer to cacheCommon changes to random value for safety reasons, so for further work need to take it back 257 | if (tmp!=cacheCommon) 258 | cacheCommon = tmp; 259 | return; 260 | 261 | } 262 | //================================================================================================= 263 | // create signature based on the current hash string 264 | void SignCurrentHash() 265 | { 266 | CacheCommon * tmp = cacheCommon; 267 | cacheCommon->signCurrentHash(&signature); 268 | // after copying signature, pointer to cacheCommon changes to random value for safety reasons, so for further work need to take it back 269 | if (tmp!=cacheCommon) 270 | cacheCommon = tmp; 271 | } 272 | //================================================================================================= 273 | // verify signature, based on current internal values 274 | void VerifyHash() 275 | { 276 | int result; 277 | cacheCommon->verifyHash(cacheCommon->getLocalHash(), &signature, &result); 278 | return; 279 | } 280 | //================================================================================================= 281 | // verify signature with key 282 | void VerifyHashByKey() 283 | { 284 | int result; 285 | cacheCommon->verifyHashByKey(cacheCommon->getLocalHash(), &signature, &key, &result); 286 | return; 287 | } 288 | //================================================================================================= 289 | // verify signature, based on current internal values 290 | void VerifySignature(wchar_t * sHash) 291 | { 292 | // create ZARRAYP structure from wchar_t input string 293 | if (!sHash) 294 | cacheCommon->logMessage(L"No data to hash"); 295 | 296 | char cHash[MAX_DATA_SIZE]; 297 | sprintf(cHash, "%S", sHash); 298 | 299 | int result; 300 | cacheCommon->verifySignature(cHash, &signature, &result); 301 | return; 302 | } 303 | //================================================================================================= 304 | // test exportKey functionality, put key into local key variable 305 | void ExportKey() 306 | { 307 | cacheCommon->exportUserKey(&key); 308 | return; 309 | } 310 | //================================================================================================= 311 | // set provider type from console 312 | void setProviderType(DWORD provTypeID) 313 | { 314 | cacheCommon->setGlobalProviderID(provTypeID); 315 | } 316 | //================================================================================================= 317 | // set algorithm ID from console 318 | void setAlgID(DWORD algID) 319 | { 320 | cacheCommon->setGlobalAlgID(algID); 321 | } 322 | //================================================================================================= 323 | // set container name from console 324 | void setContainerName(wchar_t * newContainerName) 325 | { 326 | if ((NULL != newContainerName) && (wcscmp(newContainerName, L"") != 0)) 327 | { 328 | cacheCommon->setGlobalContainerName(newContainerName); 329 | } 330 | } 331 | //================================================================================================= 332 | // set provider name from console 333 | void setProviderName(wchar_t * newProviderName) 334 | { 335 | if ((NULL != newProviderName) && (wcscmp(newProviderName, L"") != 0)) 336 | { 337 | cacheCommon->setGlobalProviderName(newProviderName); 338 | } 339 | } 340 | //================================================================================================= 341 | // set keys container pin sode from console 342 | void setContainerPIN(wchar_t * newPIN) 343 | { 344 | if ((NULL != newPIN) && (wcscmp(newPIN, L"") != 0)) 345 | { 346 | cacheCommon->setGlobalPIN(newPIN); 347 | } 348 | } 349 | //================================================================================================= 350 | // destroy local hash 351 | void DestroyHash() 352 | { 353 | cacheCommon->destroyHash(); 354 | } 355 | //================================================================================================= 356 | // print settings for current CSP 357 | void printSettings() 358 | { 359 | DWORD globalW; 360 | wchar_t * globalC; 361 | 362 | globalW = cacheCommon->getGlobalProviderID(); 363 | swprintf(tBuf, L"Provider ID: %d", globalW); 364 | cacheCommon->logMessage( tBuf ); 365 | 366 | globalC = cacheCommon->getGlobalProviderName(); 367 | swprintf(tBuf, L"Provider Name: %s", globalC); 368 | cacheCommon->logMessage( tBuf ); 369 | 370 | globalW = cacheCommon->getGlobalAlgID(); 371 | swprintf(tBuf, L"Algorithm ID: %d", globalW); 372 | cacheCommon->logMessage( tBuf ); 373 | 374 | globalC = cacheCommon->getGlobalContainerName(); 375 | swprintf(tBuf, L"Container Name: %s", globalC); 376 | cacheCommon->logMessage( tBuf ); 377 | 378 | globalC = cacheCommon->getGlobalPIN(); 379 | swprintf(tBuf, L"Container PIN: %s", globalC); 380 | cacheCommon->logMessage( tBuf ); 381 | 382 | } 383 | //================================================================================================= 384 | // fill automaticly test data for debug purposes 385 | void fillTestData() 386 | { 387 | cacheCommon->Init(75, 32798, L"CacheCrypt", L"", L"Crypto-Pro GOST R 34.10-2001 Cryptographic Service Provider"); // set parameters and acquire context 388 | cacheCommon->setLogTargets(3); // additional parameters for logging settings 389 | cacheCommon->setLogFileName(L"c:\\iscapi.log"); // additional parameter for file name in logging settings 390 | printSettings(); 391 | } 392 | //================================================================================================= 393 | //fulfill operations 394 | bool doCommand(std::vector * params) 395 | { 396 | if (!params) return false; 397 | 398 | if( !wcscmp((*params)[0], L"help") ) 399 | show_usage(); 400 | else if( !wcscmp((*params)[0], L"showProviders") ) 401 | showProviders(); 402 | else if( !wcscmp((*params)[0], L"showProvParams") ) 403 | showProviderParams(); 404 | else if( !wcscmp((*params)[0], L"print") ) 405 | printSettings(); 406 | else if ( ( !wcscmp((*params)[0], L"arContext") ) && (params->size()==2) ) 407 | acquireReleaseContext(_wtoi((*params)[1])); 408 | else if ( ( !wcscmp((*params)[0], L"aContext") ) && (params->size()==2) ) 409 | acquireContext(_wtoi((*params)[1])); 410 | else if ( ( !wcscmp((*params)[0], L"rContext") ) && (params->size()==2) ) 411 | releaseContext(_wtoi((*params)[1])); 412 | else if ( ( !wcscmp((*params)[0], L"provID") ) && (params->size()==2) ) 413 | setProviderType(_wtoi((*params)[1])); 414 | else if ( ( !wcscmp((*params)[0], L"algID") ) && (params->size()==2) ) 415 | setAlgID(_wtoi((*params)[1])); 416 | else if ( ( !wcscmp((*params)[0], L"contName") ) && (params->size()==2) ) 417 | setContainerName( (wchar_t*)((*params)[1]) ); 418 | else if ( ( !wcscmp((*params)[0], L"provName") ) && (params->size()==2) ) 419 | setProviderName( (wchar_t*)((*params)[1]) ); 420 | else if ( ( !wcscmp((*params)[0], L"contPIN") ) && (params->size()==2) ) 421 | setContainerPIN( (wchar_t*)((*params)[1]) ); 422 | else if ( ( !wcscmp((*params)[0], L"hashData") ) && (params->size()==2) ) 423 | HashData( (wchar_t*)((*params)[1]) ); 424 | else if ( ( !wcscmp((*params)[0], L"hashFile") ) && (params->size()==2) ) 425 | HashFile( (wchar_t*)((*params)[1]) ); 426 | else if ( !wcscmp((*params)[0], L"getHashValue") ) 427 | GetHashValue(); 428 | else if ( !wcscmp((*params)[0], L"destroyHash") ) 429 | DestroyHash(); 430 | else if ( !wcscmp((*params)[0], L"signCurrentHash") ) 431 | SignCurrentHash(); 432 | else if ( ( !wcscmp((*params)[0], L"signNewHash") ) && (params->size()==2) ) 433 | SignNewHash( (wchar_t*)((*params)[1]) ); 434 | else if ( !wcscmp((*params)[0], L"verifyHash") ) 435 | VerifyHash(); 436 | else if ( (!wcscmp((*params)[0], L"verifySignature") ) && (params->size()==2) ) 437 | VerifySignature((wchar_t*)((*params)[1])); 438 | else if ( !wcscmp((*params)[0], L"verifyHashByKey") ) 439 | VerifyHashByKey(); 440 | else if ( !wcscmp((*params)[0], L"exportKey") ) 441 | ExportKey(); 442 | 443 | else if ( !wcscmp((*params)[0], L"fill") ) 444 | fillTestData(); 445 | 446 | return true; 447 | } 448 | //================================================================================================= 449 | int main(int argc, wchar_t* argv[]) 450 | { 451 | setlocale(LC_CTYPE, "rus"); 452 | cacheCommon = new(CacheCommon); 453 | cacheCommon->setLogLevel(LOGLEVELALL); 454 | 455 | cacheCommon->setLogFileName(LOGFILENAME); 456 | cacheCommon->setLogTargets(LOGTARGETCONSOLE); 457 | cacheCommon->setLogSourceLocation(0); 458 | 459 | wchar_t command[1024]; 460 | std::vector params; 461 | 462 | setWindow(); 463 | show_usage(); 464 | do 465 | { 466 | printf("\n>"); 467 | _getws(command); 468 | int count = wcslen(command); 469 | 470 | if (count>0) 471 | { 472 | int nParams = parse_params(command, params); 473 | doCommand(¶ms); 474 | } 475 | 476 | } 477 | while ( wcscmp(command,L"exit") && wcscmp(command,L"quit") ); 478 | 479 | clear_vector(params); 480 | 481 | return 0; 482 | } 483 | 484 | -------------------------------------------------------------------------------- /CacheCryptoAPI/CacheCryptoAPI.cpp: -------------------------------------------------------------------------------- 1 | // This is the main DLL file. 2 | 3 | #include "stdafx.h" 4 | #include "CacheCryptoAPI.h" 5 | 6 | wchar_t dtBuf[1024]; // temporary log output buffer 7 | //================================================================================================= 8 | // Class constructor, initialize fields with empty values 9 | CacheCommon::CacheCommon() 10 | { 11 | hProv = 0; 12 | hKey = 0; 13 | hHash = 0; 14 | 15 | globalProviderID = 0; 16 | globalHashAlgID = 0; 17 | globalSignAlgID = 0; 18 | globalMKS = FALSE; 19 | globalSilentFlag = TRUE; 20 | 21 | globalPIN = NULL; 22 | globalContainerName = NULL; 23 | globalProviderName = NULL; 24 | 25 | localString = NULL; 26 | localHash.data = NULL; 27 | localHash.len = 0; 28 | localSign.data = NULL; 29 | localSign.len = 0; 30 | localKey.data = NULL; 31 | localKey.len = 0; 32 | } 33 | 34 | //================================================================================================= 35 | // Class destructor 36 | CacheCommon::~CacheCommon() 37 | { 38 | if (globalPIN) delete [] globalPIN; 39 | if (globalContainerName) delete [] globalContainerName; 40 | if (globalProviderName) delete [] globalProviderName; 41 | 42 | if (localString) delete [] localString; 43 | if (localHash.data) delete [] localHash.data; 44 | if (localSign.data) delete [] localSign.data; 45 | if (localKey.data) delete [] localKey.data; 46 | 47 | } 48 | //================================================================================================= 49 | // Function initialize parameters and calls to acquire context 50 | // provTypeId - ID of CSP 51 | // algId - algorithm ID 52 | // containerName - name of keys container, available for your CSP 53 | // pin - pin code for selected key container 54 | // providerName - name of selected CSP 55 | int CacheCommon::Init(DWORD provTypeId, DWORD algId, wchar_t *containerName, wchar_t *pin, wchar_t *providerName) 56 | { 57 | logMessage(L"Initializing cryptoprovider with following parameters:"); 58 | swprintf(dtBuf, L"\tprovider type = %i", provTypeId); logMessage(dtBuf); 59 | swprintf(dtBuf, L"\talgorithm ID = %i", algId); logMessage(dtBuf); 60 | swprintf(dtBuf, L"\tcontainer name = %s", containerName); logMessage(dtBuf); 61 | swprintf(dtBuf, L"\tcontainer pin = %s", pin); logMessage(dtBuf); 62 | swprintf(dtBuf, L"\tprovider name = %s", providerName); logMessage(dtBuf); 63 | 64 | globalProviderID = provTypeId; // set provider type from procedure parameters 65 | globalPIN = _wcsdup(pin); // set global PIN from procedure parameters with wide char duplicate 66 | globalHashAlgID = algId; // set hash algorithmID from procedure parameters 67 | 68 | if ((NULL != containerName) && (wcscmp(containerName, L"") != 0)) 69 | { 70 | globalContainerName = _wcsdup(containerName); // set keys container name from procedure parameters if it's set 71 | } 72 | if ((NULL != providerName) && (wcscmp(providerName, L"") != 0)) 73 | { 74 | globalProviderName = _wcsdup(providerName); // set provider name from procedure parameters with wide char duplicate 75 | } 76 | 77 | AcquireContext(); 78 | return 0; 79 | 80 | } 81 | //================================================================================================= 82 | // update value of localString 83 | void CacheCommon::updateLocalString(char * newString) 84 | { 85 | if (localString) 86 | { 87 | delete [] localString; 88 | localString = NULL; 89 | } 90 | localString = strdup(newString); 91 | 92 | swprintf(dtBuf, L"Local Hash updated, value is newString: %s", newString); 93 | logMessage(dtBuf); 94 | } 95 | //================================================================================================= 96 | // update localHash 97 | void CacheCommon::updateLocalHashString(char * newHashString, unsigned int newSize) 98 | { 99 | if (localHash.data) 100 | { 101 | delete [] localHash.data; 102 | localHash.data = NULL; 103 | } 104 | localHash.data = new char[newSize+1]; 105 | memcpy(localHash.data, newHashString, newSize); 106 | localHash.data[newSize]=NULL; 107 | localHash.len = newSize; 108 | } 109 | //================================================================================================= 110 | // update localSign 111 | void CacheCommon::updateLocalSignature(char * newLocalSignature, unsigned int newSize) 112 | { 113 | if (localSign.data) 114 | { 115 | delete [] localSign.data; 116 | localSign.data = NULL; 117 | } 118 | localSign.data = new char[newSize+1]; 119 | memcpy(localSign.data, newLocalSignature, newSize); 120 | localSign.data[newSize]=NULL; 121 | localSign.len = newSize; 122 | } 123 | //================================================================================================= 124 | // update localKey 125 | void CacheCommon::updateLocalKey(char * newLocalKey, unsigned int newSize) 126 | { 127 | if (localKey.data) 128 | { 129 | delete [] localKey.data; 130 | localKey.data = NULL; 131 | } 132 | localKey.data = new char[newSize+1]; 133 | memcpy(localKey.data, newLocalKey, newSize); 134 | localKey.data[newSize]=NULL; 135 | localKey.len = newSize; 136 | } 137 | //================================================================================================= 138 | // Function acquire context, every acquired context should have corresponding ReleaseContext function 139 | HCRYPTPROV CacheCommon::AcquireContext() { 140 | 141 | DWORD dwFlags = CRYPT_SILENT; 142 | BOOL result = FALSE; 143 | char* pin; 144 | 145 | logMessage(L"AcquireContext called..."); 146 | 147 | if (!globalSilentFlag) 148 | { 149 | dwFlags = 0; 150 | } 151 | 152 | if (globalMKS) 153 | { 154 | logMessage(L"Using MACHINE_KEYSET"); 155 | dwFlags |= CRYPT_MACHINE_KEYSET; 156 | } 157 | 158 | if (!globalContainerName) { 159 | if(TRUE == (result = CryptAcquireContext(&hProv, NULL, globalProviderName, globalProviderID, dwFlags))) 160 | { 161 | swprintf(dtBuf, L"Context Acquired for provType: %d", globalProviderID); 162 | logMessage(dtBuf); 163 | } 164 | } 165 | else { 166 | if(TRUE == (result = CryptAcquireContext(&hProv, globalContainerName, globalProviderName, globalProviderID, dwFlags /* | CRYPT_SILENT */))) 167 | { 168 | if (globalPIN) { 169 | pin = (char *)LocalAlloc(LMEM_ZEROINIT, wcslen(globalPIN)+1); 170 | wcstombs(pin, globalPIN, wcslen(globalPIN)+1); 171 | swprintf(dtBuf, L"Setting SIGNATURE_PIN=%s", globalPIN); 172 | logMessage(dtBuf); 173 | CryptSetProvParam(hProv, PP_SIGNATURE_PIN, (LPBYTE)pin, 0); 174 | LocalFree(pin); 175 | } 176 | swprintf(dtBuf, L"Context Acquired for ProviderType=%d, ProviderName=%s, Container=%s", globalProviderID, globalProviderName, globalContainerName); 177 | logMessage(dtBuf); 178 | } 179 | } 180 | 181 | if (result == FALSE) 182 | { 183 | logError(L"Failed to Acquire CSP Context"); 184 | } 185 | 186 | return hProv; 187 | } 188 | 189 | //================================================================================================= 190 | // Function release context after its usage is finished 191 | void CacheCommon::ReleaseContext() { 192 | logMessage(L"Releasing context..."); 193 | if (hProv) { 194 | CryptReleaseContext(hProv, 0); 195 | } 196 | hProv = 0; 197 | logLastError(); 198 | } 199 | //================================================================================================= 200 | // output providers to log file ot console 201 | void CacheCommon::printProviders() 202 | { 203 | DWORD dwIndex=0; 204 | DWORD dwType; 205 | DWORD cbName; 206 | LPTSTR pszName; 207 | 208 | logMessage(L"EnumProviders: "); 209 | 210 | while (CryptEnumProviders(dwIndex, NULL, 0, &dwType, NULL, &cbName)) 211 | { 212 | if (!cbName) break; 213 | 214 | if (!(pszName = (LPTSTR)LocalAlloc(LMEM_ZEROINIT, cbName))) return; 215 | 216 | if (!CryptEnumProviders(dwIndex++, NULL, 0, &dwType, pszName, &cbName)) 217 | { 218 | logError(L"CryptEnumProviders"); 219 | return; 220 | } 221 | swprintf(dtBuf, L"Provider Name: %s, Type: %d", pszName, dwType); 222 | logMessage( dtBuf ); 223 | LocalFree(pszName); 224 | } 225 | 226 | } 227 | //================================================================================================= 228 | // output parameters for currently selected provider, value from globalProviderID 229 | void CacheCommon::printProviderParams() 230 | { 231 | DWORD dwIndex=0; 232 | BYTE pbData[1024]; 233 | BOOL fMore = TRUE; 234 | HCRYPTPROV hCryptProv = 0; 235 | BYTE* ptr; 236 | ALG_ID aiAlgid; 237 | DWORD dwBits; 238 | DWORD dwNameLen; 239 | CHAR szName[100]; 240 | DWORD cbData = 1024; 241 | DWORD dwIncrement = sizeof(DWORD); 242 | DWORD dwFlags = CRYPT_FIRST; 243 | DWORD dwParam = PP_CLIENT_HWND; 244 | CHAR* pszAlgType = NULL; 245 | 246 | DWORD provType = getGlobalProviderID(); 247 | 248 | if (provType == 0) { 249 | logMessage(L"No ProviderType specified, please use provID command. Exiting"); 250 | } 251 | 252 | logMessage(L"Provider Params: "); 253 | 254 | hCryptProv = AcquireContext(); 255 | 256 | if (!hCryptProv) { 257 | logError(L"Context isn't acquired"); 258 | return; 259 | } 260 | 261 | // Provider Name 262 | if(CryptGetProvParam(hCryptProv, PP_NAME, pbData, &cbData, 0)) 263 | { 264 | swprintf(dtBuf, L"Provider Name=%S", pbData); 265 | logMessage( dtBuf ); 266 | } 267 | else { 268 | logError(L"Error getting ProvName"); 269 | return; 270 | } 271 | 272 | // Default Container 273 | cbData = 1024; 274 | if(CryptGetProvParam(hCryptProv, PP_CONTAINER, pbData, &cbData, 0)) 275 | { 276 | swprintf(dtBuf, L"Default Container=%S", pbData); 277 | logMessage( dtBuf ); 278 | } 279 | else { 280 | logError(L"Error getting default Container"); 281 | } 282 | 283 | // Enumerate Algs 284 | 285 | logMessage(L"Enumerating the supported algorithms"); 286 | 287 | logMessage(L" Algid Bits Type Name"); 288 | logMessage(L" _________________________________________________________"); 289 | 290 | cbData = 1024; 291 | dwFlags = CRYPT_FIRST; 292 | while(fMore) { 293 | if(CryptGetProvParam(hCryptProv, PP_ENUMALGS, pbData, &cbData, dwFlags)) 294 | { 295 | dwFlags = CRYPT_NEXT; 296 | ptr = pbData; 297 | aiAlgid = *(ALG_ID *)ptr; 298 | ptr += sizeof(ALG_ID); 299 | dwBits = *(DWORD *)ptr; 300 | ptr += dwIncrement; 301 | dwNameLen = *(DWORD *)ptr; 302 | ptr += dwIncrement; 303 | strncpy_s(szName, sizeof(szName), (char *) ptr, dwNameLen); 304 | 305 | //------------------------------------------------------- 306 | // Determine the algorithm type. 307 | switch(GET_ALG_CLASS(aiAlgid)) { 308 | case ALG_CLASS_DATA_ENCRYPT: 309 | pszAlgType = "Encrypt "; 310 | break; 311 | 312 | case ALG_CLASS_HASH: 313 | pszAlgType = "Hash "; 314 | break; 315 | 316 | case ALG_CLASS_KEY_EXCHANGE: 317 | pszAlgType = "Exchange "; 318 | break; 319 | 320 | case ALG_CLASS_SIGNATURE: 321 | pszAlgType = "Signature"; 322 | break; 323 | 324 | default: 325 | pszAlgType = "Unknown "; 326 | break; 327 | } 328 | 329 | swprintf(dtBuf,L" %8.8d %-4d %S %S", 330 | aiAlgid, 331 | dwBits, 332 | pszAlgType, 333 | szName); 334 | logMessage( dtBuf ); 335 | } 336 | else 337 | { 338 | fMore = FALSE; 339 | } 340 | } 341 | 342 | ReleaseContext(); 343 | } 344 | //================================================================================================= 345 | // Hash data string provided in parameter "hashString", stores hash result in localHash structure 346 | // hashString - string to hash and its size 347 | int CacheCommon::hashData(char * hashString) 348 | { 349 | swprintf(dtBuf, L"Initial string in (hashData) = %S", hashString); 350 | logMessage(dtBuf); 351 | 352 | // Create the hash object. 353 | if (!hashString) 354 | { 355 | logError(L"Error, no hash string passed"); 356 | return 1; 357 | } 358 | 359 | if (hHash) 360 | destroyHash(); 361 | 362 | if(CryptCreateHash(hProv, globalHashAlgID, 0, 0, &hHash)) { 363 | logMessage(L"Hash object created."); 364 | } 365 | else { 366 | logError(L"Error during CryptCreateHash."); 367 | return 1; 368 | } 369 | 370 | // Compute the cryptographic hash of the buffer. 371 | if(CryptHashData(hHash, (BYTE*)hashString, (DWORD)strlen(hashString), 0)) { 372 | updateLocalString(hashString); 373 | 374 | char sHashValue[MAX_HASH_SIZE]; 375 | CryptoRecord rHash; 376 | getHashValue(&rHash); 377 | updateLocalHashString(rHash.data, rHash.len); 378 | logMessage(L"The data buffer has been hashed."); 379 | 380 | return 0; 381 | } 382 | else { 383 | logError(L"Error during hashData."); 384 | } 385 | return 1; 386 | } 387 | //================================================================================================= 388 | // file name string provided in parameter "fileName", stores hash result in localHash structure 389 | // hashString - string to hash and its size 390 | int CacheCommon::hashFile(char * fileName) 391 | { 392 | if (!fileName) 393 | { 394 | logError(L"Filename not passed"); 395 | return 1; 396 | } 397 | 398 | FILE * file = fopen(fileName, "r"); 399 | if (!file) 400 | { 401 | logError(L"Unable to open file"); 402 | return 1; 403 | } 404 | 405 | // prepare hash structure 406 | if (hHash) 407 | destroyHash(); 408 | 409 | if(CryptCreateHash(hProv, globalHashAlgID, 0, 0, &hHash)) { 410 | logMessage(L"Hash object created."); 411 | } 412 | else { 413 | logError(L"Error during CryptCreateHash."); 414 | return 1; 415 | } 416 | 417 | // get data from file with portions and sequentally update the hash 418 | char str[1024]; 419 | while (fgets(str,1024,file)) 420 | { 421 | if(!CryptHashData(hHash, (BYTE*)str, (DWORD)strlen(str), 0)) { 422 | logError(L"Error during hashData."); 423 | destroyHash(); 424 | return 1; 425 | } 426 | } 427 | 428 | CryptoRecord rHash; 429 | getHashValue(&rHash); 430 | updateLocalHashString(rHash.data, rHash.len); 431 | logMessage(L"The data buffer has been hashed."); 432 | 433 | return 0; 434 | } 435 | //================================================================================================= 436 | // destroy previously created hash, clear localHash structure 437 | int CacheCommon::destroyHash() 438 | { 439 | if (hHash) { 440 | if (CryptDestroyHash(hHash)) 441 | { 442 | logMessage(L"Hash object destroyed"); 443 | if (localHash.data) 444 | { 445 | delete [] localHash.data; 446 | localHash.data = NULL; 447 | } 448 | localHash.len = 0; 449 | } 450 | else 451 | logMessage(L"Hash object destroyed with errors"); 452 | } 453 | else 454 | { 455 | logError(L"DestroyHash: Hash object does not exists (or already destroyed)."); 456 | } 457 | hHash = 0; 458 | return 0; 459 | } 460 | //================================================================================================= 461 | // Initialize hash with value 462 | // hashVal - value of hash string, that are going to be written to hHash 463 | int CacheCommon::initHashValue(CryptoRecord * hashVal) 464 | { 465 | BYTE* pbData; 466 | DWORD dwSigLen; 467 | char buf[MAX_HASH_SIZE]; 468 | 469 | if ( (!hashVal) || (!hashVal->data) || (hashVal->len==0) ) 470 | { 471 | logError(L"Continue verification with previously existing hash value"); 472 | return 0; 473 | } 474 | 475 | pbData = (BYTE*)LocalAlloc(LMEM_ZEROINIT, hashVal->len); 476 | memcpy(pbData, hashVal->data, hashVal->len); 477 | 478 | if (hHash) { 479 | logMessage(L"Destroying existing Hash object"); 480 | destroyHash(); 481 | } 482 | 483 | if(CryptCreateHash(hProv, globalHashAlgID, 0, 0, &hHash)) { 484 | logMessage(L"Hash object created."); 485 | } 486 | else { 487 | logError(L"Error during CryptCreateHash."); 488 | return 1; 489 | } 490 | 491 | ByteToStr(hashVal->len, pbData, buf); 492 | swprintf(dtBuf, L"Hash Received for verifying=%S", buf); 493 | logMessage(dtBuf); 494 | 495 | if (CryptSetHashParam(hHash, HP_HASHVAL, pbData, 0)) { 496 | logMessage(L"CryptSetHashParam success"); 497 | } 498 | else { 499 | logError(L"CryptSetHashParam"); 500 | LocalFree(pbData); 501 | return 1; 502 | } 503 | LocalFree(pbData); 504 | 505 | return 0; 506 | } 507 | //================================================================================================= 508 | // Return value of previously created hash, do not destroy hash 509 | // hashVal - returned hash string and its size 510 | int CacheCommon::getHashValue(CryptoRecord * hashVal) 511 | { 512 | BYTE* pbData; 513 | DWORD pdwDataLen = 0; 514 | char buf[MAX_HASH_SIZE]; 515 | 516 | if (hHash) { 517 | if (CryptGetHashParam(hHash, HP_HASHVAL, NULL, &pdwDataLen, 0)) { 518 | swprintf(dtBuf, L"Hash value data length=%d", pdwDataLen); 519 | logMessage(dtBuf); 520 | pbData = (BYTE*)LocalAlloc(LMEM_ZEROINIT, pdwDataLen + 1); 521 | if (!CryptGetHashParam(hHash, HP_HASHVAL, pbData, &pdwDataLen, 0)) { 522 | logError(L"CryprGetHashParam"); 523 | LocalFree(pbData); 524 | return 1; 525 | } 526 | else { 527 | logMessage(L"CryptGetHashParam successed"); 528 | if (hashVal) 529 | { 530 | if (hashVal->data) 531 | { 532 | delete [] hashVal->data; 533 | } 534 | hashVal->data = new char[pdwDataLen]; 535 | memcpy(hashVal->data, pbData, pdwDataLen); 536 | hashVal->len = pdwDataLen; 537 | updateLocalHashString(hashVal->data, hashVal->len); 538 | } 539 | 540 | swprintf(dtBuf, L"HashValue=%S", pbData); 541 | logMessage(dtBuf); 542 | 543 | ByteToStr(pdwDataLen, pbData, buf); 544 | swprintf(dtBuf, L"pbDataHex=%S", buf); 545 | logMessage(dtBuf); 546 | LocalFree(pbData); 547 | return 0; 548 | } 549 | } 550 | else { 551 | logError(L"CryptGetHashParam - unable to retrieve HashValue DataLen"); 552 | } 553 | } 554 | else { 555 | logError(L"Hash object does not exists"); 556 | } 557 | return 1; 558 | } 559 | //================================================================================================= 560 | // Create new hash string and sign it 561 | // hashVal - string to build hash 562 | // signVal - retuning value of signature string and its size 563 | int CacheCommon::signNewHash(char * hashVal, CryptoRecord * signVal) 564 | { 565 | DWORD dwSigLen; 566 | BYTE* pbSignature; 567 | 568 | char buf[MAX_HASH_SIZE]; 569 | 570 | if (hashData(hashVal)) 571 | return 1; 572 | 573 | // Determine the size of the signature and allocate memory. 574 | dwSigLen= 0; 575 | if (CryptSignHash(hHash, AT_KEYEXCHANGE, 0, 0, 0, &dwSigLen)) { 576 | swprintf(dtBuf, L"Signature length %d found.", dwSigLen); 577 | logMessage(dtBuf); 578 | } 579 | else { 580 | logError(L"Error during CryptSignHash for dwSigLen"); 581 | return 1; 582 | } 583 | 584 | // Allocate memory for the signature buffer. 585 | pbSignature = (BYTE *)LocalAlloc(LMEM_ZEROINIT, dwSigLen); 586 | 587 | // Sign the hash object. 588 | if (CryptSignHash(hHash, AT_KEYEXCHANGE, NULL, 0, pbSignature, &dwSigLen)) { 589 | swprintf(dtBuf, L"SignatureValue=%S", pbSignature); 590 | logMessage(dtBuf); 591 | ByteToStr(dwSigLen, pbSignature, buf); 592 | swprintf(dtBuf, L"SignatureBytes=%S", buf); 593 | logMessage(dtBuf); 594 | 595 | if (signVal) 596 | { 597 | if (signVal->data) 598 | delete [] signVal->data; 599 | } 600 | signVal->data = new char[dwSigLen]; 601 | memcpy(signVal->data, pbSignature, dwSigLen); 602 | signVal->len = dwSigLen; 603 | updateLocalSignature(signVal->data, signVal->len); 604 | } 605 | else { 606 | logError(L"Error during CryptSignHash."); 607 | LocalFree(pbSignature); 608 | return 1; 609 | } 610 | LocalFree(pbSignature); 611 | //destroyHash(); 612 | return 0; 613 | } 614 | //================================================================================================= 615 | // Sign currently available hash in system. Hash could be previously created with HashData function 616 | // signVal - retuning value of signature string and its size 617 | int CacheCommon::signCurrentHash(CryptoRecord * signVal) { 618 | DWORD dwSigLen; 619 | BYTE* pbSignature; 620 | 621 | char buf[MAX_HASH_SIZE]; 622 | 623 | logMessage(L"SignExistingHash"); 624 | 625 | // Determine the size of the signature and allocate memory. 626 | dwSigLen= 0; 627 | if (CryptSignHash(hHash, AT_KEYEXCHANGE, 0, 0, 0, &dwSigLen)) { 628 | swprintf(dtBuf, L"Signature length %d found.", dwSigLen); 629 | logMessage(dtBuf); 630 | } 631 | else { 632 | logError(L"Error during CryptSignHash for dwSigLen"); 633 | return 1; 634 | } 635 | 636 | // Allocate memory for the signature buffer. 637 | pbSignature = (BYTE *)LocalAlloc(LMEM_ZEROINIT, dwSigLen); 638 | 639 | // Sign the hash object. 640 | if (CryptSignHash(hHash, AT_KEYEXCHANGE, NULL, 0, pbSignature, &dwSigLen)) { 641 | swprintf(dtBuf, L"SignatureValue=%S", pbSignature); 642 | logMessage(dtBuf); 643 | ByteToStr(dwSigLen, pbSignature, buf); 644 | swprintf(dtBuf, L"SignatureBytes=%S", buf); 645 | logMessage(dtBuf); 646 | 647 | if (signVal) 648 | { 649 | if (signVal->data) 650 | delete [] signVal->data; 651 | } 652 | signVal->data = new char[dwSigLen]; 653 | memcpy(signVal->data, pbSignature, dwSigLen); 654 | signVal->len = dwSigLen; 655 | updateLocalSignature(signVal->data, signVal->len); 656 | } 657 | else { 658 | logError(L"Error during CryptSignHash."); 659 | LocalFree(pbSignature); 660 | return 1; 661 | } 662 | LocalFree(pbSignature); 663 | //destroyHash(); 664 | return 0; 665 | } 666 | //================================================================================================= 667 | // Verify signature by hash 668 | // hashVal - hashed string and its size 669 | // signVal - signed hash string and its size 670 | // result - operation result: 1-success, 0-failure 671 | int CacheCommon::verifyHash(CryptoRecord * hashVal, CryptoRecord * signVal, int *result) 672 | { 673 | BYTE* pbData = NULL; 674 | DWORD dwSigLen = 0; 675 | BYTE* pbSignature = NULL; 676 | char buf[MAX_HASH_SIZE]; 677 | 678 | *result = 0; 679 | 680 | swprintf(dtBuf, L"Hash Received for verifying=%S", hashVal->data); 681 | logMessage(dtBuf); 682 | 683 | 684 | if (initHashValue(hashVal)==1) 685 | { 686 | logError(L"initHashValue"); 687 | return 1; 688 | } 689 | 690 | //Verify Signature 691 | if(!CryptGetUserKey(hProv, AT_KEYEXCHANGE, &hKey)) { 692 | logError(L"CryptGetUserKey"); 693 | return 1; 694 | } 695 | else { 696 | logMessage(L"CryptGetUserKey: public key acquired"); 697 | } 698 | 699 | dwSigLen = signVal->len; 700 | pbSignature = (BYTE *)LocalAlloc(LMEM_ZEROINIT, dwSigLen); 701 | memcpy(pbSignature, signVal->data, dwSigLen); 702 | 703 | ByteToStr(dwSigLen, pbSignature, buf); 704 | swprintf(dtBuf, L"Signature received=%S", buf); 705 | logMessage(dtBuf); 706 | 707 | if (CryptVerifySignature(hHash, pbSignature, dwSigLen, hKey, NULL, 0)) { 708 | logMessage(L"Hash is verified"); 709 | *result = 1; 710 | } 711 | else { 712 | logError(L"Hash is NOT verified"); 713 | } 714 | LocalFree(pbSignature); 715 | CryptDestroyKey(hKey); 716 | 717 | return 0; 718 | } 719 | //================================================================================================= 720 | int CacheCommon::verifySignature(char * hashString, CryptoRecord * signVal, int *result) 721 | { 722 | *result = 0; 723 | // hash data, returned 0 is success 724 | if (hashData(hashString)) 725 | return 1; 726 | //verify Hash, returned 0 is success 727 | if (verifyHash(getLocalHash(), signVal, result)) 728 | return 1; 729 | 730 | return 0; 731 | } 732 | //================================================================================================= 733 | // Verify signature by hash and key 734 | // hashVal - hashed string and its size 735 | // signVal - signed hash string and its size 736 | // pubKey - key string, used to sign hash, and its size 737 | // result - operation result: 1-success, 0-failure 738 | int CacheCommon::verifyHashByKey(CryptoRecord * hashVal, CryptoRecord * signVal, CryptoRecord * pubKey, int * result) 739 | { 740 | BYTE* pbData = NULL; 741 | DWORD dwSigLen = 0; 742 | BYTE* pbSignature = NULL; 743 | char buf[MAX_HASH_SIZE]; 744 | 745 | *result = 0; 746 | 747 | swprintf(dtBuf, L"Hash Received for verifying=%S", hashVal->data); 748 | logMessage(dtBuf); 749 | 750 | if (initHashValue(hashVal)==1) 751 | { 752 | logError(L"initHashValue"); 753 | return 1; 754 | } 755 | 756 | // verify signature 757 | if (!CryptImportKey(hProv, (BYTE*)pubKey->data, pubKey->len, 0, 0, &hKey)) { 758 | logError(L"CryptImportKey"); 759 | return 1; 760 | } 761 | else { 762 | logMessage(L"CryptImportKey: key imported"); 763 | } 764 | 765 | ByteToStr(signVal->len, signVal->data, buf); 766 | swprintf(dtBuf, L"Signature received=%S", buf); 767 | logMessage(dtBuf); 768 | 769 | 770 | // verify signature 771 | if (CryptVerifySignature(hHash, (BYTE*)signVal->data, signVal->len, hKey, NULL, 0)) { 772 | logMessage(L"Signature is verified"); 773 | *result = 1; 774 | } 775 | else { 776 | logError(L"Signature is NOT verified"); 777 | } 778 | LocalFree(pbSignature); 779 | CryptDestroyKey(hKey); 780 | 781 | return 0; 782 | } 783 | //================================================================================================= 784 | // Build key string ready to transfer 785 | // keyVal - resulting key string and its size, can be later transfered to recieving side 786 | int CacheCommon::exportUserKey(CryptoRecord * keyVal) { 787 | BYTE* pbKeyBlob; 788 | DWORD dwBlobLen = 0; 789 | 790 | char buf[MAX_HASH_SIZE]; 791 | 792 | if (!CryptGetUserKey(hProv, AT_KEYEXCHANGE, &hKey)) { 793 | logError(L"GetUserKey"); 794 | return 1; 795 | } 796 | 797 | if(CryptExportKey(hKey, 0, PUBLICKEYBLOB, 0, NULL, &dwBlobLen)) { 798 | swprintf(dtBuf,L"Size of the BLOB for the public key=%d", dwBlobLen); 799 | logMessage(dtBuf); 800 | } 801 | else { 802 | logError(L"CryptExportKey: Error computing BLOB length"); 803 | } 804 | 805 | pbKeyBlob = (BYTE*)LocalAlloc(LMEM_ZEROINIT, dwBlobLen); 806 | 807 | if(CryptExportKey(hKey, 0, PUBLICKEYBLOB, 0, pbKeyBlob, &dwBlobLen)) { 808 | ByteToStr(dwBlobLen, pbKeyBlob, buf); 809 | swprintf(dtBuf,L"Contents has been written to the BLOB, = %S", buf); 810 | logMessage(dtBuf); 811 | if (keyVal) 812 | { 813 | if (keyVal->data) 814 | delete [] keyVal->data; 815 | } 816 | keyVal->data = new char[dwBlobLen]; 817 | memcpy(keyVal->data, pbKeyBlob, dwBlobLen); 818 | keyVal->len = dwBlobLen; 819 | } 820 | else { 821 | logError(L"Error during CryptExportKey"); 822 | LocalFree(pbKeyBlob); 823 | return 1; 824 | } 825 | return 0; 826 | } 827 | //================================================================================================= 828 | void CacheCommon::ByteToStr( 829 | DWORD cb, 830 | void* pv, 831 | LPSTR sz) 832 | { 833 | BYTE* pb = (BYTE*) pv; // local pointer to a BYTE in the BYTE array 834 | DWORD i; // local loop counter 835 | int b; // local variable 836 | 837 | // Begin processing loop. 838 | for (i = 0; i> 4; 841 | *sz++ = (b <= 9) ? b + '0' : (b - 10) + 'A'; 842 | b = *pb & 0x0F; 843 | *sz++ = (b <= 9) ? b + '0' : (b - 10) + 'A'; 844 | pb++; 845 | } 846 | *sz++ = 0; 847 | } 848 | 849 | //================================================================================================= 850 | void CacheCommon::ByteToZARRAY(int len, unsigned char *buf, ZARRAYP bytestr) 851 | { 852 | unsigned char *p, *q; 853 | 854 | p = buf; 855 | q = bytestr->data; 856 | 857 | bytestr->len = len; 858 | while(len--) *q++ = *p++; 859 | 860 | } 861 | //================================================================================================= 862 | void CacheCommon::ReverseByteToZARRAY(int len, unsigned char *buf, ZARRAYP bytestr) 863 | { 864 | unsigned char *p, *q; 865 | 866 | p = buf; 867 | q = bytestr->data; 868 | 869 | bytestr->len = len; 870 | while(len--) *(q + len) = *p++; 871 | 872 | } --------------------------------------------------------------------------------