Commit 266cef8c authored by Oleg Korshul's avatar Oleg Korshul

tests windows

parent a5e821cd

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sha1_C14N", "ConsoleApplication1\Sha1_C14N.csproj", "{A945E071-111A-41E0-8BB0-4F7755EBB77B}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{A945E071-111A-41E0-8BB0-4F7755EBB77B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A945E071-111A-41E0-8BB0-4F7755EBB77B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A945E071-111A-41E0-8BB0-4F7755EBB77B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A945E071-111A-41E0-8BB0-4F7755EBB77B}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
</configuration>
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using System.Security.Cryptography.X509Certificates;
using System.IO;
namespace Sha1_C14N
{
class Program
{
static void Main(string[] args)
{
XmlDocument docStripped = new XmlDocument();
//docStripped.Load(@"D:\GIT\core\DesktopEditor\xmlsec\test\windows_list_serts\Debug\debug\document.xml");
docStripped.Load("D:\\444.txt");
XmlDsigC14NTransform t = new XmlDsigC14NTransform();
t.LoadInput(docStripped);
Stream s = (Stream)t.GetOutput(typeof(Stream));
BinaryReader br = new BinaryReader(s);
byte[] b = br.ReadBytes((int)s.Length);
File.Delete("D:\\1.txt");
var fileStream = File.Create("D:\\1.txt");
s.Seek(0, SeekOrigin.Begin);
s.CopyTo(fileStream);
fileStream.Close();
s.Seek(0, SeekOrigin.Begin);
SHA1 sha1 = SHA1.Create();
byte[] hash = sha1.ComputeHash(s);
string base64String = Convert.ToBase64String(hash);
FileStream fRes = File.Create("D:\\res.bin");
fRes.Write(hash, 0, hash.Length);
fRes.Close();
SHA1 sha33 = SHA1.Create();
byte[] hash33 = sha33.ComputeHash(b);
string base64String2 = Convert.ToBase64String(hash33);
FileStream s1 = File.OpenRead(@"D:\GIT\core\DesktopEditor\xmlsec\test\windows_list_serts\Debug\debug\document2.xml");
SHA1 sha11 = SHA1.Create();
byte[] hash11 = sha11.ComputeHash(s1);
string base64_11 = Convert.ToBase64String(hash11);
X509Store my = new X509Store(StoreName.My, StoreLocation.CurrentUser);
my.Open(OpenFlags.ReadOnly);
// Find the certificate we’ll use to sign
RSACryptoServiceProvider csp = null;
foreach (X509Certificate2 cert in my.Certificates)
{
string sName = cert.Subject;
if (cert.Subject.Contains("Oleg.Korshul"))
{
csp = (RSACryptoServiceProvider)cert.PrivateKey;
break;
}
}
byte[] signedData = csp.SignHash(hash11, CryptoConfig.MapNameToOID("SHA1"));
string signedDataBase64 = Convert.ToBase64String(signedData);
Console.WriteLine(base64_11);
}
}
}
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Управление общими сведениями о сборке осуществляется с помощью
// набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
// связанные со сборкой.
[assembly: AssemblyTitle("Sha1_C14N")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Sha1_C14N")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Параметр ComVisible со значением FALSE делает типы в сборке невидимыми
// для COM-компонентов. Если требуется обратиться к типу в этой сборке через
// COM, задайте атрибуту ComVisible значение TRUE для этого типа.
[assembly: ComVisible(false)]
// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
[assembly: Guid("a945e071-111a-41e0-8bb0-4f7755ebb77b")]
// Сведения о версии сборки состоят из следующих четырех значений:
//
// Основной номер версии
// Дополнительный номер версии
// Номер сборки
// Редакция
//
// Можно задать все значения или принять номера сборки и редакции по умолчанию
// используя "*", как показано ниже:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{A945E071-111A-41E0-8BB0-4F7755EBB77B}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ConsoleApplication1</RootNamespace>
<AssemblyName>ConsoleApplication1</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Security" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
\ No newline at end of file
......@@ -20,6 +20,12 @@ void MyHandleError(char *s);
bool Sign(HCERTSTORE hStoreHandle, PCCERT_CONTEXT pCertContext, std::wstring sFileXml, std::wstring sSignatureFile);
bool Verify(HCERTSTORE hStoreHandle, PCCERT_CONTEXT pCertContext, std::wstring sFileXml, std::wstring sSignatureFile);
void ConvertEndian(const BYTE* src, BYTE* dst, DWORD size)
{
for(BYTE* p = dst + size - 1; p >= dst; ++src, --p)
(*p) = (*src);
}
void main(void)
{
......@@ -312,8 +318,8 @@ void main(void)
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool bRes = true;
bRes = Sign(hCertStore, pCertContext, NSFile::GetProcessDirectory() + L"/document.xml", NSFile::GetProcessDirectory() + L"/result.txt");
bRes = Verify(hCertStore, pCertContext, NSFile::GetProcessDirectory() + L"/document.xml", NSFile::GetProcessDirectory() + L"/result.txt");
bRes = Sign(hCertStore, pCertContext, NSFile::GetProcessDirectory() + L"/document2.xml", NSFile::GetProcessDirectory() + L"/result.txt");
bRes = Verify(hCertStore, pCertContext, NSFile::GetProcessDirectory() + L"/document2.xml", NSFile::GetProcessDirectory() + L"/result.txt");
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CertFreeCertificateContext(pCertContext);
......@@ -342,8 +348,6 @@ bool Sign(HCERTSTORE hStoreHandle, PCCERT_CONTEXT pCertContext, std::wstring sFi
DWORD dwSigLen = 0;
BYTE* pbSignature = NULL;
// Open the certificate store.
bResult = CryptAcquireCertificatePrivateKey(pCertContext, 0, NULL, &hCryptProv, &dwKeySpec, NULL);
bool bIsResult = ((dwKeySpec & AT_SIGNATURE) == AT_SIGNATURE);
......@@ -357,6 +361,23 @@ bool Sign(HCERTSTORE hStoreHandle, PCCERT_CONTEXT pCertContext, std::wstring sFi
bResult = CryptHashData(hHash, pDataSrc, dwFileSrcLen, 0);
if (true)
{
DWORD cbHashSize = 0, dwCount = sizeof(DWORD);
BOOL b1 = CryptGetHashParam(hHash, HP_HASHSIZE, (BYTE*)&cbHashSize, &dwCount, 0);
BYTE* pDataHashRaw = new BYTE[dwCount];
BOOL b2 = CryptGetHashParam(hHash, HP_HASHVAL, pDataHashRaw, &cbHashSize, 0);
char* pBase64_hash = NULL;
int nBase64Len_hash = 0;
NSFile::CBase64Converter::Encode(pDataHashRaw, (int)cbHashSize, pBase64_hash, nBase64Len_hash, NSBase64::B64_BASE64_FLAG_NONE);
delete [] pBase64_hash;
}
// Sign the hash object
dwSigLen = 0;
bResult = CryptSignHash(hHash, dwKeySpec, NULL, 0, NULL, &dwSigLen);
......@@ -364,18 +385,27 @@ bool Sign(HCERTSTORE hStoreHandle, PCCERT_CONTEXT pCertContext, std::wstring sFi
pbSignature = new BYTE[dwSigLen];
bResult = CryptSignHash(hHash, dwKeySpec, NULL, 0, pbSignature, &dwSigLen);
NSFile::CFileBinary oFileTmp;
oFileTmp.CreateFileW(NSFile::GetProcessDirectory() + L"/HASH.bin");
oFileTmp.WriteFile(pbSignature, dwSigLen);
oFileTmp.CloseFile();
BYTE* pbSignatureMem = new BYTE[dwSigLen];
ConvertEndian(pbSignature, pbSignatureMem, dwSigLen);
NSFile::CFileBinary oFile;
oFile.CreateFileW(sSignatureFile);
//oFile.WriteFile(pbSignature, dwSigLen);
char* pBase64 = NULL;
int nBase64Len = 0;
NSFile::CBase64Converter::Encode(pbSignature, (int)dwSigLen, pBase64, nBase64Len, NSBase64::B64_BASE64_FLAG_NONE);
NSFile::CBase64Converter::Encode(pbSignatureMem, (int)dwSigLen, pBase64, nBase64Len, NSBase64::B64_BASE64_FLAG_NONE);
oFile.WriteFile((BYTE*)pBase64, (DWORD)nBase64Len);
oFile.CloseFile();
delete[] pbSignature;
delete[] pbSignatureMem;
delete[] pDataSrc;
bResult = CryptDestroyHash(hHash);
......@@ -409,18 +439,22 @@ bool Verify(HCERTSTORE hStoreHandle, PCCERT_CONTEXT pCertContext, std::wstring s
NSFile::CBase64Converter::Decode((char*)pDataHashBase64, (int)dwFileHashSrcLenBase64, pDataHash, nTmp);
dwHashLen = (DWORD)nTmp;
BYTE* pDataHashMem = new BYTE[dwHashLen];
ConvertEndian(pDataHash, pDataHashMem, dwHashLen);
bResult = CryptHashData(hHash, pDataSrc, dwFileSrcLen, 0);
// Get the public key from the certificate
CryptImportPublicKeyInfo(hCryptProv, PKCS_7_ASN_ENCODING | X509_ASN_ENCODING, &pCertContext->pCertInfo->SubjectPublicKeyInfo, &hPubKey);
bResult = CryptVerifySignature(hHash, pDataHash, dwHashLen, hPubKey, NULL, 0);
BOOL bResultRet = CryptVerifySignature(hHash, pDataHashMem, dwHashLen, hPubKey, NULL, 0);
delete[] pDataSrc;
delete[] pDataHash;
delete[] pDataHashMem;
delete[] pDataHashBase64;
bResult = CryptDestroyHash(hHash);
return bResult;
return bResultRet && bResult;
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment